我有一個應該啓動線程的程序。爲了避免退出軟件,線程以無限循環運行,並加入線程。這個線程永遠不會返回一個值。所以現在我有問題,我調用pthread_cancel valgrind檢測到內存泄漏。我怎樣才能避免這種內存泄漏?如何通過使用pthread_cancel來避免內存泄漏?
Valgrind的輸出:
==5673== 136 bytes in 1 blocks are possibly lost in loss record 4 of 8
==5673== at 0x4026A68: calloc (vg_replace_malloc.c:566)
==5673== by 0x40111FB: _dl_allocate_tls (dl-tls.c:300)
==5673== by 0x404E5A0: [email protected]@GLIBC_2.1 (allocatestack.c:580)
==5673== by 0x804C44E: start (mythread.c:25)
==5673== by 0x804D128: main (main.c:10)
代碼:
int main(){
signal(SIGINT,cleanup);
signal(SIGQUIT,cleanup);
signal(SIGSEGV,cleanup);
start();
return 0;
}
int start()
{
pthread_create(&thread_id[0],NULL,&threadhandler,NULL);
pthread_join(thread_id[0],NULL);
return err;
}
void cleanup(){
pthread_cancel(thread_id[0]);
exit(0);
}
void cleanup_tcp(void *p){
}
void* threadhandler(void *arg)
{
(void) arg;
int status = 0;
while(TRUE){
pthread_cleanup_push(cleanup_tcp,NULL);
pthread_testcancel();
fprintf(stderr,"Run\n");
pthread_cleanup_pop(0);
}
return NULL;
}
拆卸螺紋(通過調用'pthread_detach()')取消它可以幫助(位)之前。 – alk