zhangsongcui

Provider and Customer problem

Nov 6th, 2011
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.97 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <mutex>
  4. #include <condition_variable>
  5. #include <deque>
  6. #include <chrono>
  7.  
  8. using namespace std;
  9.  
  10. deque<int> pipe;
  11. mutex globalMutex;
  12. condition_variable cond;
  13.  
  14. void provider()
  15. {
  16.     int value;
  17.     while (cin >> value)
  18.     {
  19.         {
  20.             lock_guard<mutex> lock(globalMutex);
  21.             pipe.push_back(value);
  22.         }
  23.         cond.notify_all();
  24.     }
  25. }
  26.  
  27. void customer()
  28. {
  29.     mutex mut;
  30.     unique_lock<mutex> lock(mut);
  31.     while (!pipe.empty() || cin.good())     // Is deque::empty() atomic operation? So is cin.good()?
  32.     {
  33.         cond.wait( lock, [] { return !pipe.empty(); } );
  34.         {
  35.             lock_guard<mutex> lock(globalMutex);
  36.             cout << "You enterred:" << pipe.front() << endl;
  37.             pipe.pop_front();
  38.         }
  39.         this_thread::sleep_for(chrono::seconds(4));
  40.     }
  41. }
  42.  
  43. int main()
  44. {
  45.     thread t1(provider), t2(customer);
  46.     t1.join();
  47.     t2.join();
  48. }
  49.  
  50.  
Advertisement
Add Comment
Please, Sign In to add comment