SpaceCreator

pingpong

Apr 20th, 2019
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.72 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <mutex>
  4. #include <condition_variable>
  5.  
  6. std::mutex m;
  7. std::condition_variable ping_done;
  8. std::condition_variable pong_done;
  9.  
  10. void bar(){
  11.     std::unique_lock <std::mutex> lock(m);
  12.     for(size_t i = 0; i < 500000; ++i) {
  13.         ping_done.wait(lock);
  14.         printf("pong\n");
  15.         pong_done.notify_one();
  16.     }
  17. }
  18.  
  19. void foo(){
  20.     std::unique_lock <std::mutex> lock(m);
  21.     for(size_t i = 0; i < 500000; ++i) {
  22.         printf("ping\n");
  23.         ping_done.notify_one();
  24.         pong_done.wait(lock);
  25.     }
  26. }
  27.  
  28.  
  29.  
  30. int main(int argc, char const *argv[]) {
  31.     std::thread T1 (bar);
  32.     T1.detach();
  33.     std::thread T2 (foo);
  34.     T2.join();
  35.     return 0;
  36. }
Advertisement
Add Comment
Please, Sign In to add comment