Pthread导致的memory leak

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在解决客户的一个内存泄露的问题,客户提供了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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JXES智能生态系统

如文章对你有用,请作者喝个咖啡

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值