fork(1) download
  1. #include <iostream>
  2. #include <chrono>
  3. #include <thread>
  4. #include <condition_variable>
  5. #include <mutex>
  6.  
  7. const std::chrono::seconds MainDelay = std::chrono::seconds(5);
  8. const std::chrono::seconds WorkerTimeResolution = std::chrono::seconds(2);
  9. std::mutex cv_m;
  10. std::condition_variable cv;
  11. bool _execute = false;
  12.  
  13. void worker_thread() {
  14. std::unique_lock<std::mutex> lk(cv_m);
  15. while (cv.wait_for(lk,WorkerTimeResolution,[](){return _execute ;})) {
  16. // do stuff as long _execute is true
  17. std::cout << "Worker thread executing ..." << std::endl;
  18. std::this_thread::sleep_for(WorkerTimeResolution);
  19. }
  20. }
  21.  
  22. int main() {
  23. std::thread t(worker_thread);
  24. _execute = true;
  25. cv.notify_all();
  26.  
  27. for(int i = 0; i < 3; ++i) {
  28. // Do other stuff, may be with more varying timing conditions ...
  29. std::this_thread::sleep_for(MainDelay);
  30. std::cout << "Main thread executing ..." << std::endl;
  31. }
  32. _execute = false;
  33. cv.notify_all();
  34. t.join();
  35. }
Time limit exceeded #stdin #stdout 5s 11656KB
stdin
Standard input is empty
stdout
Worker thread executing ...
Worker thread executing ...
Worker thread executing ...
Main thread executing ...
Worker thread executing ...
Worker thread executing ...
Main thread executing ...
Worker thread executing ...