今天在解决客户的一个内存泄露的问题,客户提供了source code,但从代码语法,代码结构上的检查,都没有发现什么问题,编码风格还算整洁,那为什么还有Memory Leak?
客户代码有一个特点,使用了多线程,而且用得还比较频繁,而且初看代码,也没有问题,线和有创建pthread_create, 都会有退出pthread_exit,那问题在那里,于是,就查看了下linux的api手册,仔细研究了下linux 的thread.
##Linux如此说
A thread may either be joinable or detached. If a thread is joinable, then another thread can call
pthread_join(3) to wait for the thread to terminate and fetch its exit status. Only when a terminated joinable
thread has been joined are the last of its resources released back to the system. When a detached thread termi‐
nates, its resources are automatically released back to the system: it is not possible to join with the thread in
order to obtain its exit status. Making a thread detached is useful for some types of daemon threads whose exit
status the application does not need to care about. By default, a new thread is created in a joinab

本文探讨了在Linux环境中,多线程编程中由于使用Pthread可能导致的内存泄漏问题。官方解释了joinable和detached两种线程状态,指出在joinable状态下,pthread_exit不会释放资源,而detach状态或使用pthread_join可以避免资源泄漏。文章提供了三种防止内存泄漏的方法,包括在线程中调用pthread_detach,创建时指定PTHREAD_CREATE_DETACHED属性,以及使用pthread_join等待线程结束。
最低0.47元/天 解锁文章
809

被折叠的 条评论
为什么被折叠?



