Advertisement
Guest User

race on boost::shared_ptr copies

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