5

当线程被添加到 boost::thread_group 时,例如:

boost::thread_group my_threads;
boost::thread *t = new boost::thread( &someFunc );
my_threads.add_thread(th);

my_threads只有当对象超出范围时,才会删除所有创建的 boost::thread 对象。但是我的程序主线程在执行时会产生很多线程。因此,如果已经完成了大约 50 个线程,则程序使用大约1.5Gb的内存,并且仅在主进程终止时才释放该内存。

问题是:线程函数完成后如何删除这些 boost::thread 对象?!

4

1 回答 1

6

您可以这样做,但请注意同步(最好使用共享指针来 boost::thread_group 而不是引用,除非您确定该线程组将存活足够长的时间):

void someFunc(..., boost::thread_group & thg, boost::thread * thisTh)
{
  // do sth

  thg.remove_thread(thisThr);
  delete thisTh; // we coud do this as thread of execution and boost::thread object are quite independent
}

void run()
{
  boost::thread_group my_threads;
  boost::thread *t = new boost::thread(); // invalid handle, but we need some memory placeholder, so we could pass it to someFunc
  *t = boot::thread(
    boost::bind(&someFunc, boost::ref(my_threads), t)
  );
  my_threads.add_thread(t);
  // do not call join
}

您还可以检查 at_thread_exit() 函数。

无论如何, boost::thread 对象的重量不应为 30 MB。

于 2012-05-21T10:32:46.317 回答