关于pthread_detach(pthread_self())

本文介绍了如何通过pthread_detach(pthread_self())实现子线程自我分离,以确保子线程结束时资源能立即回收,避免内存泄露。

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

被创建的子线程也可以自己分离自己,子线程调用pthread_detach(pthread_self())就是分离自己,因为pthread_self()这个函数返回的就是自己本身的线程ID。


目的:该子线程止时底层资源立即被回收,防止内存不能释放造成内存泄露。

引用\[1\]中提到了pthread_detach(pthread_self())的用法,它将线程的状态改为unjoinable状态,确保资源的释放。这个函数通常在线程内部调用。引用\[2\]和引用\[3\]分别给出了使用pthread_detachpthread_join的不同顺序的示例代码。 在引用\[2\]中,先调用了pthread_detach(pthread_self()),然后在主线程中调用pthread_join(tid, NULL)。这种情况下,pthread_join会返回错误码22,表示无效的参数。因为线程已经被设置为unjoinable状态,所以无法再使用pthread_join来等待线程的结束。 在引用\[3\]中,先调用了pthread_join(tid, NULL),然后在线程内部调用pthread_detach(pthread_self())。这种情况下,pthread_join会成功返回0,表示成功等待线程的结束。因为线程已经被设置为unjoinable状态,所以即使在主线程中调用pthread_join也不会出错。 综上所述,如果先调用pthread_detach(pthread_self()),再调用pthread_join会导致pthread_join返回错误码22,表示无效的参数。而如果先调用pthread_join,再调用pthread_detach(pthread_self()),则不会出错。 #### 引用[.reference_title] - *1* [【彻底弄懂】linux中pthread_detach()的作用](https://blog.youkuaiyun.com/Set_Mode/article/details/121439463)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [linux线程 (1)——初始线程与线程控制](https://blog.youkuaiyun.com/m0_59337025/article/details/127989768)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值