c++ - 线程本身终止时如何删除boost线程对象?

标签 c++ boost boost-thread

当线程被添加到 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/

相关文章:

c++ - 派生类和智能指针

c++ - 如何禁用有关某些库的编译器警告?

c++ - boost 互斥量抛出(奇数?)异常

winapi - 将 boost::thread->native_handle() 转换为 XP ThreadId

c++ - opencv 使用 mask 和修复将一幅图像覆盖在另一幅图像上

c++ - C++中的抽象类与接口(interface)

c++ - 使用 boost over socket 发送和接收压缩文件

c++ - 使用 boost 库的多线程

c# - 在 CSCore 中实现均衡器,例如 Foobar 的 SuperEQ

C++ 不明确的运算符重载错误