当线程被添加到 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对象?!
最佳答案
你可以这样做,但要注意同步(最好使用指向 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。
关于c++ - 线程本身终止时如何删除boost线程对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10682205/