fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <thread>
  4. #include <mutex>
  5. #include <condition_variable>
  6.  
  7. std::mutex m;
  8. std::condition_variable cv;
  9. std::string data;
  10. bool ready = false;
  11. bool processed = false;
  12.  
  13. void worker_thread()
  14. {
  15. // Wait until main() sends data
  16. std::unique_lock<std::mutex> lk(m, std::defer_lock);
  17. cv.wait(lk, []{return ready;});
  18.  
  19. // after the wait, we own the lock.
  20. std::cout << "Worker thread is processing data\n";
  21. data += " after processing";
  22.  
  23. // Send data back to main()
  24. processed = true;
  25. std::cout << "Worker thread signals data processing completed\n";
  26.  
  27. // Manual unlocking is done before notifying, to avoid waking up
  28. // the waiting thread only to block again (see notify_one for details)
  29. lk.unlock();
  30. cv.notify_one();
  31. }
  32.  
  33. int main()
  34. {
  35. std::thread worker(worker_thread);
  36. std::this_thread::sleep_for(std::chrono::seconds(1));
  37.  
  38. data = "Example data";
  39. // send data to the worker thread
  40. {
  41. std::lock_guard<std::mutex> lk(m);
  42. ready = true;
  43. std::cout << "main() signals data ready for processing\n";
  44. }
  45. cv.notify_one();
  46.  
  47. // wait for the worker
  48. {
  49. std::unique_lock<std::mutex> lk(m);
  50. cv.wait(lk, []{return processed;});
  51. }
  52. std::cout << "Back in main(), data = " << data << '\n';
  53.  
  54. worker.join();
  55. }
Runtime error #stdin #stdout #stderr 0s 12680KB
stdin
Standard input is empty
stdout
main() signals data ready for processing
Worker thread is processing data
Worker thread signals data processing completed
stderr
terminate called after throwing an instance of 'std::system_error'
  what():  Operation not permitted