fork download
  1. #include <iostream>
  2. #include <thread>
  3. #include <condition_variable>
  4. #include <chrono>
  5. #include <atomic>
  6.  
  7. using namespace std;
  8. using namespace std::chrono;
  9.  
  10. int main()
  11. {
  12. auto worker = [](mutex& m,
  13. atomic<bool>& done,
  14. atomic<bool>& main_done,
  15. condition_variable& notify_main,
  16. condition_variable& wait_main,
  17. uint32_t workload)
  18. {
  19. unique_lock<mutex> ul(m);
  20. while (true)
  21. {
  22. while (main_done == false)
  23. wait_main.wait(ul, [&]{ return main_done.load(); });
  24.  
  25. this_thread::sleep_for(milliseconds(workload));
  26. done.store(true);
  27. cout << this_thread::get_id() << " job done." << endl;
  28.  
  29. notify_main.notify_one();
  30. }
  31. };
  32.  
  33. //----------------------------------------------------------------------
  34.  
  35. mutex main_m1, main_m2;
  36. condition_variable cv, cv1, cv2;
  37. atomic<bool> job1_done(false), job2_done(false), main_job(false);
  38.  
  39. thread th1(worker, std::ref(main_m1), std::ref(job1_done),
  40. std::ref(main_job), std::ref(cv1), std::ref(cv), 300);
  41. thread th2(worker, std::ref(main_m2), std::ref(job2_done),
  42. std::ref(main_job), std::ref(cv2), std::ref(cv), 400);
  43.  
  44. th1.detach();
  45. th2.detach();
  46.  
  47. //----------------------------------------------------------------------
  48.  
  49. mutex m1, m2;
  50. unique_lock<mutex> ul1(m1), ul2(m2);
  51. high_resolution_clock::time_point p = high_resolution_clock::now();
  52.  
  53. while (true)
  54. {
  55. main_job = true;
  56. cv.notify_all();
  57.  
  58. this_thread::sleep_for(milliseconds(100));
  59. cout << "main job done." << endl;
  60.  
  61. while (job1_done == false || job2_done == false)
  62. {
  63. cv1.wait(ul1, [&]{ return job1_done.load(); });
  64. cv2.wait(ul2, [&]{ return job2_done.load(); });
  65. }
  66.  
  67. job2_done = false;
  68. job1_done = false;
  69. main_job = false;
  70.  
  71. double dur = duration_cast<milliseconds>(high_resolution_clock::now() - p).count();
  72. p = high_resolution_clock::now();
  73. cout << dur << endl;
  74. }
  75.  
  76. return 0;
  77. }
Runtime error #stdin #stdout #stderr 0s 3476KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
terminate called after throwing an instance of 'std::system_error'
  what():  Enable multithreading to use std::thread: Operation not permitted