Linux 线程导致的内存泄漏分析及解决
时间:2010-07-29 来源:poseidonqiu
pthread_create (&thread, NULL, &thread_function, NULL); 就这么写了,参数2没有设置线程结束后自动detach,并且没有使用pthread_join或pthread_detach释放执行结束后线程的空 间!
代码
1 // 最简单的办法,在线程执行结束后调用 pthread_detach让他自己释放
2 pthread_detach(pthread_self());
3
4
5 // 或者创建线程前设置 PTHREAD_CREATE_DETACHED 属性
6 pthread_attr_t attr;
7 pthread_t thread;
8 pthread_attr_init (&attr);
9 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
10 pthread_create (&thread, &attr, &thread_function, NULL);
11 pthread_attr_destroy (&attr);
Linux man page 里有已经说明了这个问题:
When a joinable thread terminates, its memory resources (thread descriptor and stack) are not deallocated until another thread performs pthread_join on it. Therefore, pthread_join must be called once for each joinable thread created to avoid memory leaks.
也就说线程执行完后如果不join的话,线程的资源会一直得不到释放而导致内存泄漏!一时的图快后患无穷啊。
解决办法:

2 pthread_detach(pthread_self());
3
4
5 // 或者创建线程前设置 PTHREAD_CREATE_DETACHED 属性
6 pthread_attr_t attr;
7 pthread_t thread;
8 pthread_attr_init (&attr);
9 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
10 pthread_create (&thread, &attr, &thread_function, NULL);
11 pthread_attr_destroy (&attr);
第2行的那种方法最简单,在线程函数尾部加上这句话就可以将线程所占用的资源给释放掉;或者像 5-11 所示的方法设置detach属性,这样也会在线程return/pthread_exit后释放内存。
其实仔细想想,valgrind检查时已经提示了pthread_create没有释放的问题,只是之前没引起注意。其实这样的问题也只有在长时间 运行时,慢慢积累这一点点的内存才会暴露出来,看来valgrind的提示也不能置之不理啊。
相关阅读 更多 +
排行榜 更多 +