pneave

Using conditional variable and mutex

Dec 20th, 2017
312
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None | 0 0
  1.  
  2. // Using conditional variable and mutex
  3. void function_1() {
  4.     int count = 10;
  5.     while (count > 0) {
  6.         std::unique_lock<mutex> locker(mu);
  7.         q.push_front(count);
  8.         locker.unlock();
  9.         cond.notify_one();  // Notify one waiting thread, if there is one.
  10.         std::this_thread::sleep_for(chrono::seconds(1));
  11.         count--;
  12.     }
  13. }
  14.  
  15. void function_2() {
  16.     int data = 0;
  17.     while ( data != 1) {
  18.         std::unique_lock<mutex> locker(mu);
  19.         cond.wait(locker, [](){ return !q.empty();} );  // Unlock mu and wait to be notified
  20.             // relock mu
  21.         data = q.back();
  22.         q.pop_back();
  23.         locker.unlock();
  24.         cout << "t2 got a value from t1: " << data << endl;
  25.     }
  26. }
  27.  
  28. int main() {
  29.     std::thread t1(function_1);
  30.     std::thread t2(function_2);
  31.     t1.join();
  32.     t2.join();
  33.     return 0;
  34. }
Advertisement
Add Comment
Please, Sign In to add comment