Advertisement
Guest User

Untitled

a guest
Jan 21st, 2015
299
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.07 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <mutex>
  4. #include <memory>
  5.  
  6. struct Consumer {
  7.   void consume(const std::shared_ptr<int> aBar)
  8.   {
  9.     const std::lock_guard<std::mutex> myLock(theMutex);
  10.     thePtr = aBar;
  11.   }
  12.  
  13.   void main_loop() {
  14.     while(1) {
  15.       std::shared_ptr<int> myLocal;
  16.       {
  17.         const std::lock_guard<std::mutex> myLock(theMutex);
  18.         myLocal = thePtr;
  19.       }
  20.       myLocal.use_count();
  21.     }
  22.   }
  23.  
  24.   std::shared_ptr<int> thePtr;
  25.   std::mutex           theMutex;
  26. };
  27.  
  28. struct Producer {
  29.   Producer(Consumer& aConsumer) : theConsumer(aConsumer) {}
  30.   void main_loop() {
  31.     while(1) {
  32.       std::shared_ptr<int> myBar(new int(3));
  33.       theConsumer.consume(myBar);
  34.       myBar.use_count();
  35.     }
  36.   }
  37.  
  38.   Consumer& theConsumer;
  39. };
  40.  
  41. int main() {
  42.   Consumer myConsumer;
  43.   Producer myProducer(myConsumer);
  44.  
  45.   std::thread myConsumerThread(&Consumer::main_loop, std::ref(myConsumer));
  46.   std::thread myProducerThread(&Producer::main_loop, std::ref(myProducer));
  47.  
  48.   myProducerThread.join();
  49.   myConsumerThread.join();
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement