Advertisement
Guest User

Untitled

a guest
Nov 23rd, 2014
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <functional>
  4. #include <mutex>
  5. #include <queue>
  6. #include <vector>
  7. #include <atomic>
  8. #include <string>
  9. #include <chrono>
  10. #include <cmath>
  11.  
  12. using namespace std;
  13.  
  14. template <typename T>
  15. class ThreadsafeQueue {
  16. mutable mutex mut;
  17. queue<T> data_queue;
  18.  
  19. public:
  20. ThreadsafeQueue() {};
  21.  
  22. void push(T value)
  23. {
  24. mut.lock();
  25. data_queue.push(value);
  26. mut.unlock();
  27. }
  28.  
  29. bool try_pop(T& value)
  30. {
  31. mut.lock();
  32. if (data_queue.empty()) {
  33. mut.unlock();
  34. return false;
  35. }
  36.  
  37. value = data_queue.front();
  38. data_queue.pop();
  39. mut.unlock();
  40. return true;
  41. }
  42.  
  43. bool empty() const
  44. {
  45. mut.lock();
  46. bool is_empty = data_queue.empty();
  47. mut.unlock();
  48. return is_empty;
  49. }
  50.  
  51. };
  52.  
  53. class ThreadPool {
  54. atomic_bool done;
  55. ThreadsafeQueue <function<void()>> tasks_queue;
  56. unsigned int threads_num;
  57. vector<thread> threads;
  58.  
  59. void thread_worker()
  60. {
  61. while (!done) {
  62. function<void()> task;
  63. if (tasks_queue.try_pop(task))
  64. task();
  65. else
  66. this_thread::yield();
  67. }
  68. }
  69.  
  70. public:
  71. ThreadPool(unsigned int num): done(false)
  72. {
  73. threads_num = num;
  74. cout << "threads_num = " << threads_num << endl;
  75. try
  76. {
  77. for (unsigned int i = 0; i < threads_num; i++) {
  78. cout << "Thread в„– " << i << endl;
  79. threads.push_back(thread(&ThreadPool::thread_worker, this));
  80. }
  81. }
  82. catch(...)
  83. {
  84. done = true;
  85. throw;
  86. }
  87. }
  88.  
  89. ~ThreadPool()
  90. {
  91. done = true;
  92. for(vector<thread>::iterator it = threads.begin(); it != threads.end(); it++)
  93. it->join();
  94. }
  95.  
  96. template<class _FN, class... _ARGS>
  97. void submit(_FN _fn, _ARGS... _args)
  98. {
  99. tasks_queue.push(bind(_fn, _args...));
  100. }
  101. };
  102.  
  103. void factorize(long num)
  104. {
  105. // cout is not thread safe, so if strings are messed up, it's Ok
  106. cout << "factorize: thread #" << this_thread::get_id() << ": ";
  107. int i = 2;
  108. while (i <= sqrt(num)) {
  109. if(num%i == 0) {
  110. cout << " " << i;
  111. num = num/i;
  112. } else i++;
  113. }
  114. cout << " " << num << endl;
  115. }
  116.  
  117.  
  118. int main()
  119. {
  120. ThreadPool thread_pool(5);
  121.  
  122. for (unsigned int i = 20; i < 25; i++)
  123. thread_pool.submit(&factorize, i);
  124.  
  125. fflush(stdout);
  126. return 0;
  127. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement