fork download
  1. #include <iostream>
  2. #include <thread>
  3. #include <future>
  4. #include <mutex>
  5. #include <deque>
  6. #include <atomic>
  7. using namespace std;
  8.  
  9.  
  10. std::deque<std::packaged_task<int()>>task_q;
  11. std::mutex lock9;
  12. std::atomic<int>finished{0};
  13.  
  14. int factial_calc2(int in)
  15. {
  16. cout <<"start calc "<<in<<endl;
  17. int ret = 1;
  18. for (int i = in; i > 1; i--)
  19. {
  20. ret = ret*i;
  21. }
  22. //std::lock_guard<std::mutex> locker(lock9);
  23. std::cout << "input is " << in << "result is " << ret << std::endl;
  24. cout <<"end calc "<<in<<endl;
  25.  
  26. return ret;
  27. }
  28.  
  29. void test_thread9_producer1()
  30. {
  31. cout <<"start producer1"<<endl;
  32. for (int i = 0; i < 10; i = i + 2)
  33. {
  34. std::lock_guard<std::mutex> locker(lock9);
  35. std::packaged_task<int()> t1(std::bind(factial_calc2, i));
  36. task_q.push_back(std::move(t1));
  37. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  38. }
  39. finished++;
  40. cout <<"end producer1"<<endl;
  41. }
  42.  
  43. void test_thread9_producer2()
  44. {
  45. cout <<"start producer2"<<endl;
  46. for (int i = 1; i < 10; i = i + 2)
  47. {
  48. std::lock_guard<std::mutex> locker(lock9);
  49. std::packaged_task<int()> t1(std::bind(factial_calc2, i));
  50. task_q.push_back(std::move(t1));
  51. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  52. }
  53. cout <<"end producer2"<<endl;
  54. finished++;
  55. }
  56.  
  57.  
  58. void test_thread9_consumer1()
  59. {
  60. bool nothing_to_do{false};
  61. cout <<"consumer1"<<endl;
  62. while (!nothing_to_do && finished<2)
  63. {
  64. std::packaged_task<int()>t;
  65. {
  66. std::lock_guard<std::mutex> locker(lock9);
  67. cout<< "Loop remaining "<< task_q.size() <<endl;
  68. nothing_to_do=task_q.empty();
  69. if (!nothing_to_do)
  70. {
  71. t = std::move(task_q.front());
  72. task_q.pop_front();
  73. }
  74. }
  75. if (t.valid())
  76. t();
  77. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  78. }
  79. cout<<"end consumer"<<endl;
  80. }
  81.  
  82. void test_thread9()
  83. {
  84. std::thread t1(test_thread9_producer1);
  85. std::thread t2(test_thread9_producer2);
  86. std::thread t3(test_thread9_consumer1);
  87.  
  88. t1.join();
  89. t2.join();
  90. t3.join();
  91. }
  92.  
  93.  
  94. int main() {
  95. test_thread9();
  96. return 0;
  97. }
Success #stdin #stdout 0s 29088KB
stdin
Standard input is empty
stdout
consumer1
Loop remaining 0
start producer2
start producer1
end consumer
end producer2
end producer1