Did*_*nov 5 c++ boost boost-thread
将线程添加到boost :: thread_group时:
boost::thread_group my_threads;
boost::thread *t = new boost::thread( &someFunc );
my_threads.add_thread(th);
Run Code Online (Sandbox Code Playgroud)
只有当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
}
Run Code Online (Sandbox Code Playgroud)
您还可以检查at_thread_exit()函数.
无论如何,boost :: thread对象的重量不应超过30 MB.
| 归档时间: |
|
| 查看次数: |
4266 次 |
| 最近记录: |