当boost :: thread_group终止时,它是否会自动从boost :: thread_group中删除?

时间:2012-02-25 21:07:28

标签: c++ multithreading boost boost-thread

This question虽然相似,却没有真正回答我的问题。)

我已经problems with my own "thread group" implementation,并且没有更接近解决甚至找出问题,我正在考虑使用boost::thread_grp

现在,从documentation I can find on the subject 1 开始,我一直认为线程对象 - 无论其实际工作的持续时间 - 仍然存在并且是线程组的一部分,直到线程组被破坏。

然而,粗略测试似乎表明boost::thread_group::size()随着线程的工作和终止而自行减少。这意味着线程对象本身也正在为我清理。

这是真的吗?我能依靠吗?

#include <cassert>
#include <unistd.h>         // for sleep()
#include <boost/thread.hpp>

boost::mutex m;
unsigned int count = 0;

void func() {
   boost::mutex::scoped_lock l(m);
   count++;
}

int main()
{
   boost::thread_group grp;
   for (size_t i = 0; i < 300; i++)
      grp.create_thread(func());

   sleep(10);

   assert(count == 300);
   assert(grp.size() == 0);  // passes, in my tests

   // ^ Can I rely on that?
   //   Do I really have no thread objects eating up
   //     memory, at this point?

   grp.join_all();
   // ^ Then I guess this is doing nothing, in this case...
}

如果是,那么我的整个原始has_threads实施只是一个破碎的克隆,我浪费了我的时间。 :)

而且,是的,assert对于这个片段来说是一个非常糟糕的选择,因为我猜这可能会导致任何不太可能出现的线程在过去曾经count的情况下屠杀内存?无论如何,没关系。


1 - 我坚持使用Boost 1.40,但有关此事的文档似乎与更新版本相同。


更新

This thread就是一个例子,人们说我的测试结果与之相反。如果是这样的话,它也提供了一个不错的解决方案;很好thread_group完全是线程安全的(尽管我不相信shared_ptr::get()是线程安全的;如果线程在shared_ptr::reset完成之前结束了怎么办?)。我是否需要使用此解决方案?

1 个答案:

答案 0 :(得分:4)

不,我错误地解释了我的测试结果,没有抽象出为我创建线程的任务调度程序。简而言之,我正在检查错误的size()上的boost::thread_group

事实上,boost::thread_group::size() 在线程终止时不会自行关闭,所以我将使用论坛帖子中提供的an adapted version解决方案在更新问题中链接。

相关问题