Advertisement
zhangsongcui

PingPang test

Jul 31st, 2016
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.90 KB | None | 0 0
  1. #include <cstdio>
  2. #include <thread>
  3. #include <condition_variable>
  4. #include <mutex>
  5. #include <chrono>
  6.  
  7. int main() {
  8.     enum { COUNT = 1000000 };
  9.     volatile int ping = 0, pang = 0;
  10.     auto clock = std::chrono::high_resolution_clock::now();
  11.     std::condition_variable cvPing, cvPang;
  12.     std::mutex mtx;
  13.  
  14.     std::thread thd([&](){
  15.         cvPing.notify_all();
  16.         std::unique_lock<std::mutex> lock(mtx);
  17.         while (pang < COUNT) {
  18.             cvPang.wait(lock);
  19.             ++pang;
  20.             cvPing.notify_all();
  21.         }
  22.     });
  23.  
  24.     {
  25.         std::unique_lock<std::mutex> lock(mtx);
  26.         while (ping < COUNT) {
  27.             cvPing.wait(lock);
  28.             ++ping;
  29.             cvPang.notify_all();
  30.         }
  31.     }
  32.  
  33.     thd.join();
  34.     std::printf("PING: %d, PANG: %d, Time used: %lldms\n", ping, pang, (std::chrono::high_resolution_clock::now() - clock).count() / 1000000);
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement