【发布时间】:2015-03-04 10:11:25
【问题描述】:
我已经为此奋斗了很长时间。环顾四周,我似乎无法找到答案。我只是创建了两个分离的线程,然后在它们上都使用pthread_exit(),但时不时会出现泄漏。
因为我知道人们会问我:
- 是的,我已阅读所有其他问题,但没有真正的答案
- 我将线程标记为
detached - 我给
enough time让线程初始化并终止 - 我已经阅读了 pthread_exit 的手册,并且使用正确
- 与
-Wall编译良好strong>
代码:
int threads_keepalive = 1;
void* thread_do(void *arg){
while(threads_keepalive)
sleep(1);
pthread_exit(NULL);
}
int main(){
/* Make threads */
pthread_t* threads;
threads = malloc(2 * sizeof(pthread_t));
pthread_create(&threads[0], NULL, thread_do, NULL);
pthread_create(&threads[1], NULL, thread_do, NULL);
pthread_detach(threads[0]);
pthread_detach(threads[1]);
sleep(1); // MAKING SURE THREADS HAVE INITIALIZED
/* Kill threads */
threads_keepalive = 0;
sleep(5); // MAKING SURE THREADS HAVE UNBLOCKED
free(threads);
return 0;
}
运行该代码,虽然它是正确的(至少在我看来),但我会随机出现内存泄漏。我使用valgrind 多次运行相同的测试,如下所示
> gcc test.c -pthread -o test && for i in {1..100}; do valgrind --leak-check=full --track-origins=yes ./test 2>&1 | grep frees; done
==4088== total heap usage: 8 allocs, 4 frees, 2,230 bytes allocated
==4211== total heap usage: 8 allocs, 4 frees, 2,230 bytes allocated
==4337== total heap usage: 8 allocs, 4 frees, 2,230 bytes allocated
==4463== total heap usage: 8 allocs, 4 frees, 2,230 bytes allocated
==4590== total heap usage: 8 allocs, 8 frees, 2,230 bytes allocated
==4717== total heap usage: 8 allocs, 8 frees, 2,230 bytes allocated
==4853== total heap usage: 8 allocs, 4 frees, 2,230 bytes allocated
==4981== total heap usage: 8 allocs, 8 frees, 2,230 bytes allocated
==5110== total heap usage: 8 allocs, 8 frees, 2,230 bytes allocated
==5239== total heap usage: 8 allocs, 8 frees, 2,230 bytes allocated
..
发生了什么事??
更新:创建一个线程而不是两个线程不会显示内存泄漏。
【问题讨论】:
-
好吧,首先你应该阅读 pthread_create() 的手册,特别是 thread_start() 的签名。
-
没有
thread_start()函数。你在说什么WTF? -
它在手册页上。在您的代码中,“thread_do()”应采用 void* 参数。我并不是说这肯定会对你的结果产生任何影响,但你是如此坚持以至于你检查了这么多东西......
-
看,把 void* 放进去。大约需要 5 秒钟,然后一个可能的 UB 来源就被消灭了。
-
void* thread_do(void *param){...
标签: c memory-leaks pthreads valgrind