join后线程上的共享指针计数为1?
有一个等待线程完成的 boost::condition_variable
:
boost::condition_variable mContd;
boost::shared_ptr<boost::thread> mThread;
想象一下,该线程之前已启动一段时间,现在等待:
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
}
那么,这个计数何时设置为零?我假设,在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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
use_count()
只是告诉您有多少shared_ptr
对象指向同一个boost::thread
对象。它与线程是否终止无关。当 mThread 超出范围时,计数器将自动递减。
如果您不再需要
thread
对象,您可以调用mThread.reset()
。这也会导致 mThread.use_count() 降至零。use_count()
simply tells you how manyshared_ptr
object points to the sameboost::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 callmThread.reset()
. That'll also causemThread.use_count()
to go down to zero.对象无法像这样正确地删除自己。
当线程终止时,表示它的 boost::thread 对象进入“完成”状态,但它必须仍然“存在”,因为
shared_ptr 正在控制它。您仍然拥有之前的那个现在“已完成”的
boost::thread
对象,因此计数仍然为 1。事实上,一般来说,
boost::shared_ptr:: use_count()
仅在表示“空指针”而不是实际存在的对象时返回0
。一个直接的类比如下:
Objects can't properly delete themselves like that.
When the thread terminates, the
boost::thread
object representing it goes into a "finished" state, but it must still "exist" becauseshared_ptr
is controlling it. You still have the one, now-"finished"boost::thread
object that you have before, so the count is still 1.In fact, in general,
boost::shared_ptr::use_count()
will only return0
when it's representing a "null pointer" rather than an actual object that exists.A direct analogy follows: