Search code examples
c++shared-ptrboost-thread

Shared Pointer on a thread counts 1 after join?


Having a boost::condition_variable which waits for a thread to complete:

boost::condition_variable mContd;
boost::shared_ptr<boost::thread> mThread;

Imagine, the Thread was started some time before, and now wait:

if(!mContd.timed_wait(tLock, boost::posix_time::seconds(1))) {
  // cancel thread if deadline is reached
  mThread.interrupt();
  mThread.join();

  std::cout 
    << "Thread count = " 
    << mThread.use_count() // still prints '1'
    << std::endl;

} else {
  // continue
}

So, when is this count set to a zero? I assumed, after a join a thread is finished. But when it is?


Solution

  • use_count() simply tells you how many shared_ptr object points to the same boost::thread object. It has nothing to do with whether the thread has terminated.

    The counter will automatically get decremented when mThread goes out of scope.

    If you no longer need the thread object, you could call mThread.reset(). That'll also cause mThread.use_count() to go down to zero.