2011-09-02 41 views
2

每當我在我的程序中運行valgrind時,它告訴我無論在哪裏調用pthread_create,都可能會丟失內存。我一直在試圖遵循pthread_create內存泄漏?

valgrind memory leak errors when using pthread_create http://gelorakan.wordpress.com/2007/11/26/pthead_create-valgrind-memory-leak-solved/

等各種網站指導谷歌給了我,但沒有奏效。到目前爲止,我嘗試加入線程,將pthread_attr_t設置爲DETACHED,在每個線程上調用pthread_detach,並調用pthread_exit()。

試圖PTHREAD_CREATE_DETACHED -

pthread_attr_t attr; 
pthread_attr_init(&attr); 
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 

pthread_create(&c_udp_comm, &attr, udp_comm_thread, (void*)this); 
pthread_create(&drive, &attr, driving_thread, (void*)this); 
pthread_create(&update, &attr, update_server_thread(void*)this); 

我想我可能已經編碼與加盟錯誤此下一個......我被 https://computing.llnl.gov/tutorials/pthreads/ 會和他們有數組中的所有它們的線程所以他們只是for循環。但是我沒有把它們都放在一個數組中,所以我試圖改變它的工作方式。請告訴我,如果我做錯了。

void* status; 
pthread_attr_t attr; 
pthread_attr_init(&attr); 
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); 

pthread_create(&c_udp_comm, &attr, udp_comm_thread, (void*)this); 
pthread_create(&drive, &attr, driving_thread, (void*)this); 
pthread_create(&update, &attr, update_server_thread(void*)this); 

pthread_join(c_udp_comm, &status); 
pthread_join(drive, &status); 
pthread_join(update, &status); 

試圖pthread_detach -

pthread_create(&c_udp_comm, NULL, udp_comm_thread, (void*)this); 
pthread_create(&drive, NULL, driving_thread, (void*)this); 
pthread_create(&update, NULL, update_server_thread(void*)this); 

pthread_detach(c_udp_comm); 
pthread_detach(drive); 
pthread_detach(update); 

嘗試了pthread_exit -

pthread_create(&c_udp_comm, NULL, udp_comm_thread, (void*)this); 
pthread_create(&drive, NULL, driving_thread, (void*)this); 
pthread_create(&update, NULL, update_server_thread(void*)this); 

pthread_exit(NULL); 

如果有人可以幫助我弄清楚爲什麼沒有的,這是工作,我將非常感激。

回答

4

glibc在線程退出時不釋放線程堆棧;它緩存它們以供重用,並且只在緩存變大時修剪它。因此它總是「泄漏」一些內存。

1

您可以通過使用pthread_join代碼並重復創建/加入過程幾次證明沒有泄漏。你會發現「泄漏」的內存量並沒有改變,證明沒有內存實際上被泄露。