Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. class threadPool{
  2. public:
  3. explicit threadPool(int n) : run(true) {
  4. assert(n > 1 && n < 16, "number of thread");
  5. for (int i = 0; i < n; i++) {
  6. threads.emplace_back(std::thread([this] {
  7. while (run) {
  8. std::unique_lock<std::mutex> lock(mtx);
  9. cond.wait(lock, [this] {return !tasks.empty() && run; });
  10. while (!tasks.empty()) {
  11. auto task = std::move(tasks.front());
  12. task();
  13. tasks.pop();
  14. }
  15. }
  16. }));
  17. }
  18. }
  19.  
  20. ~threadPool() {
  21. stop();
  22. }
  23.  
  24. template <typename Func, class... Args>
  25. std::future<typename std::result_of<Func(Args...)>::type> add(Func&& func, Args&&... args) {
  26. typedef typename std::result_of<Func(Args...)>::type return_type;
  27. if (run) {
  28. std::lock_guard<std::mutex> lock(mtx);
  29. auto t = std::make_shared<std::packaged_task<return_type()>>(std::bind(std::forward<Func>(func), std::forward<Args>(args)...));
  30. auto ret = t->get_future();
  31. tasks.emplace([t] {
  32. (*t)();
  33. });
  34. cond.notify_one();
  35. return std::move(ret);
  36. }
  37. }
  38.  
  39. void stop() {
  40. for (std::thread &thread : threads) {
  41. thread.join();
  42. }
  43. cond.notify_all();
  44. run = false;
  45. }
  46.  
  47. private:
  48. bool run;
  49. std::mutex mtx;
  50. std::condition_variable cond;
  51. std::vector<std::thread> threads;
  52. std::queue<std::function<void()>> tasks;
  53. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement