1

我正在尝试提升线程,我从 valgrind 注意到它只是通过循环一个空的代码块泄漏了 320 个字节。我从 2010 年开始在 google 上发现了一些帖子,这些帖子表明它们可能是由于线程在 valgind 运行之前未关闭而导致的误报,但这略有不同。在这些示例中,您有一些仍然可以访问的块(因此,如果线程仍在运行,则可以释放)其中我的运行显示 8 个仍然可以访问,而 20 个块肯定丢失了。这是我应该担心的事情,还是我错过了什么?谢谢

编码

#include <boost/thread.hpp>
#include <iostream>
#define THREADS 20

void threadfunc(int workerid) {}

int main(int argc, char **argv){

    boost::thread *threads[THREADS];
    int i;
    for (i = 0; i < THREADS; i++) {
        threads[i] = new boost::thread(threadfunc, i);
    }
    for (i = 0; i < THREADS; i++) {
        threads[i]->join();
    }
}

编译命令

 c++ -o example example.cpp -I /usr/include/boost -lboost_system -lboost_thread

Valgind 命令

 G_SLICE=always-malloc G_DEBUG=gc-friendly  valgrind -v --tool=memcheck --leak-check=full --show-reachable=yes --num-callers=40 --log-file=valgrind.log ./example

Valgine结果

==31674== HEAP SUMMARY:
==31674==     in use at exit: 328 bytes in 21 blocks
==31674==   total heap usage: 103 allocs, 82 frees, 14,968 bytes allocated
==31674==
==31674== Searching for pointers to 21 not-freed blocks
==31674== Checked 215,920 bytes
==31674==
==31674== 8 bytes in 1 blocks are still reachable in loss record 1 of 2
==31674==    at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==31674==    by 0x4E454A9: boost::detail::get_once_per_thread_epoch() (in /usr/lib/libboost_thread.so.1.46.1)
==31674==    by 0x4E3E4FF: ??? (in /usr/lib/libboost_thread.so.1.46.1)
==31674==    by 0x4E3E7C8: boost::detail::get_current_thread_data() (in /usr/lib/libboost_thread.so.1.46.1)
==31674==    by 0x4E3FF3A: boost::thread::join() (in /usr/lib/libboost_thread.so.1.46.1)
==31674==    by 0x402C79: main (in /home/Jason/php/base/example)
==31674==
==31674== 320 bytes in 20 blocks are definitely lost in loss record 2 of 2
==31674==    at 0x4C2B1C7: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==31674==    by 0x402C2A: main (in /home/Jason/php/base/example)
==31674==
==31674== LEAK SUMMARY:
==31674==    definitely lost: 320 bytes in 20 blocks
==31674==    indirectly lost: 0 bytes in 0 blocks
==31674==      possibly lost: 0 bytes in 0 blocks
==31674==    still reachable: 8 bytes in 1 blocks
==31674==         suppressed: 0 bytes in 0 blocks
==31674==
==31674== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 2 from 2)
--31674--
--31674-- used_suppression:      2 dl-hack3-cond-1
==31674==
==31674== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 2 from 2)
4

1 回答 1

5

这是你的错误,而不是boost::threads。你的内存没有被释放。

for (i = 0; i < THREADS; i++) {
    threads[i] = new boost::thread(threadfunc, i);
}

在退出主函数之前,您必须释放内存(删除线程)。就像是

for (i = 0; i < THREADS; i++) {
   delete threads[i];
}

或加入后删除下一个。

于 2012-12-12T06:57:43.140 回答