簡體   English   中英

Boost線程中的內存泄漏?

[英]Memory leaks in boost threads?

我正在嘗試增強線程,並且從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

預設命令

 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

精氨酸結果

==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)

這是您的錯誤,而不是boost::thread 您的記憶沒有被釋放。

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

從主功能退出之前,您必須釋放內存(刪除線程)。 就像是

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

或加入后刪除下一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM