【问题标题】:How to delete boost thread object when thread itself terminates?线程本身终止时如何删除提升线程对象?
【发布时间】:2012-05-27 18:34:13
【问题描述】:

当线程被添加到 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对象?!

【问题讨论】:

  • 我相信这个问题是类似的:stackoverflow.com/questions/3970818/…
  • @Naveen,我确实需要一个可以在主线程请求时中断所有池子线程的包装器。在您链接的问题中,他们建议只创建一个线程并从中分离 boost::thread 对象。

标签: c++ boost boost-thread


【解决方案1】:

你可以这样做,但要注意同步(最好使用共享指针来 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。

【讨论】:

  • 感谢您的解决方案。在等待答案的同时,也想到了将 boost::thread 指针发送给线程函数。
  • 我在 2 台 Gentoo 机器和 1 台 FreeBSD 上使用 htop。在 Gentoo 机器上,当创建并运行 15 个线程时,htop 的 VIRT 列显示约 450MB。在具有相同线程数的 FreeBSD 上,VIRT 列显示 ~65300KB。我很困惑
  • 我意识到那是在看错误的列。 RES 在所有机器上显示大约 33mb。顺便说一句,您在线程中调用 thg.remove_thread(thisThr) 而不使用互斥锁。安全吗?!
  • boost 1.31 的文档指出 所有 thread_group 成员函数都是线程安全的,除了破坏。 这句话在 boost 1.49 文档中没有,但是,在 Breaking Changes 表示这发生了变化。我会假设,thread_group 是线程安全的。
猜你喜欢
  • 1970-01-01
  • 2017-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多