Advertisement
dooly386

wait for thread safe

May 13th, 2019
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | None | 0 0
  1. #include <iostream>
  2. #include <condition_variable>
  3. #include <thread>
  4. #include <chrono>
  5.  
  6. std::condition_variable cv;
  7. std::mutex cv_m; // This mutex is used for three purposes:
  8.                  // 1) to synchronize accesses to i
  9.                  // 2) to synchronize accesses to std::cerr
  10.                  // 3) for the condition variable cv
  11. int i = 0;
  12.  
  13. void waits()
  14. {
  15.     std::unique_lock<std::mutex> lk(cv_m);
  16.     std::cerr << "Waiting... \n";
  17.     cv.wait(lk, []{return i == 1;});
  18.     std::cerr << "...finished waiting. i == 1\n";
  19. }
  20.  
  21. void signals()
  22. {
  23.     std::this_thread::sleep_for(std::chrono::seconds(1));
  24.     {
  25.         std::lock_guard<std::mutex> lk(cv_m);
  26.         std::cerr << "Notifying...\n";
  27.     }
  28.     cv.notify_all();
  29.  
  30.     std::this_thread::sleep_for(std::chrono::seconds(1));
  31.  
  32.     {
  33.         std::lock_guard<std::mutex> lk(cv_m);
  34.         i = 1;
  35.         std::cerr << "Notifying again...\n";
  36.     }
  37.     cv.notify_all();
  38. }
  39.  
  40. int main()
  41. {
  42.     std::thread t1(waits), t2(waits), t3(waits), t4(signals);
  43.     t1.join();
  44.     t2.join();
  45.     t3.join();
  46.     t4.join();
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement