【问题标题】:Boost thread Leakage C++Boost线程泄漏C++
【发布时间】:2011-09-13 09:02:58
【问题描述】:

有人可以告诉我 boost 线程库是否泄漏。在我看来,它确实: 谷歌说我应该用我正在做的 boost thread 和 pthread 进行编译,并且在 1.40 版中这个问题已经得到解决,但我仍然得到泄漏。请注意,这可以正常编译,但会检测到泄漏。

#include <boost/thread.hpp>  
#include <boost/date_time.hpp>  

void t1(){}

int main(void){
boost::thread th1(t1);
th1.join();
return 1;
}

使用 Valgrind 我得到以下输出

HEAP SUMMARY:
==8209==     in use at exit: 8 bytes in 1 blocks
==8209==   total heap usage: 5 allocs, 4 frees, 388 bytes allocated
==8209== 
==8209== 8 bytes in 1 blocks are still reachable in loss record 1 of 1
==8209==    at 0x4024F20: malloc (vg_replace_malloc.c:236)
==8209==    by 0x4038CCB: boost::detail::get_once_per_thread_epoch() (in /usr/local/lib/libboost_thread.so.1.42.0)
==8209==    by 0x40329D4: ??? (in /usr/local/lib/libboost_thread.so.1.42.0)
==8209==    by 0x4032B26: boost::detail::get_current_thread_data() (in /usr/local/lib/libboost_thread.so.1.42.0)
==8209==    by 0x4033F32: boost::thread::join() (in /usr/local/lib/libboost_thread.so.1.42.0)
==8209==    by 0x804E7C3: main (testboost.cpp)
==8209== 
==8209== LEAK SUMMARY:
==8209==    definitely lost: 0 bytes in 0 blocks
==8209==    indirectly lost: 0 bytes in 0 blocks
==8209==      possibly lost: 0 bytes in 0 blocks
==8209==    still reachable: 8 bytes in 1 blocks
==8209==         suppressed: 0 bytes in 0 blocks

我还尝试了以下网站上列出的代码:http://antonym.org/2009/05/threading-with-boost---part-i-creating-threads.html 还是一样的问题。

【问题讨论】:

  • 查看 boost 源代码中的 src/pthread/Once.cpp。很明显它没有泄漏(只需查找它使用的 pthread 库函数的定义)。
  • 使用std::thread而不是boost,代码甚至不能为我运行;它以std::system_error 异常终止。
  • 只需尝试上面链接中的代码,您很可能会看到来自 valgrind 的泄漏

标签: c++ multithreading boost memory-leaks valgrind


【解决方案1】:

这与 boost 1_46_1 有关,因此对于您使用的版本可能不是这样。如果您真的想说服自己,请查看提升来源。 (当我运行您的示例代码时,OSX 上的泄漏检测器未检测到任何泄漏)。

这不是真正的泄漏(除非 pthreads、您使用的过时版本的 boost 或您的编译器存在错误)。

get_once_per_thread_epoch malloc 分配一个新的uintmax_t 并将其映射到带有epoch_tss_key 的线程本地存储中,该epoch_tss_key 具有释放映射数据的关联析构函数。因此保证分配的内存被释放。

我真的不明白为什么 valgrind 会将此检测为泄漏,但这可能是因为 pthreads 退出函数在 valgrind 之后的某个时间点执行。另一种可能性是 pthread 函数本身正在泄漏,但我在文档中没有看到任何表明这种情况的内容。

【讨论】:

  • 谢谢。我从 valgrind 升级到 1.46.1 和同样的错误。直接用 pthread 编码不会导致这个错误。必须像你说的那样,在 valgrind 检测到之后就完成了线程的清理
猜你喜欢
  • 1970-01-01
  • 2020-08-08
  • 1970-01-01
  • 2013-07-28
  • 1970-01-01
  • 1970-01-01
  • 2020-04-06
  • 1970-01-01
  • 2022-10-05
相关资源
最近更新 更多