线程相关函数(3)-pthread_detach()将某个线程设成分离态
#include <pthread.h>
int pthread_detach(pthread_t tid);
pthread_t tid: 分离线程的tid
返回值:成功返回0,失败返回错误号。
一般情况下,线程终止后,其终止状态一直保留到其它线程调用pthread_join获取它的状态为止。但是线程也可以被置为detach状态,这样的线程一旦终止就立刻回收它占用的所有资源,而不保留终止状态。不能对一个已经处于detach状态的线程调用pthread_join,这样的调用将返回EINVAL。如果已经对一个线程调用了pthread_detach就不能再调用pthread_join了。
通常情况下,若创建一个线程不关心它的返回值,也不想使用pthread_join来回收(调用pthread_join的进程会阻塞),就可以使用pthread_detach,将该线程的状态设置为分离态,使线程结束后,立即被系统回收。
示例代码:
#include <pthread.h> #include <stdio.h> #include <string.h> #include <unistd.h> void *thr_fn(void *arg) { int n = 10; while(n--) { printf("thread count %d\n", n); sleep(1); } return (void *)1; } int main() { pthread_t tid; void *retval; int err; pthread_create(&tid, NULL, thr_fn, NULL); pthread_detach(tid); while(1) { err = pthread_join(tid, &retval); if (err != 0) fprintf(stderr, "thread %s\n", strerror(err)); else fprintf(stderr, "thread exit code %d\n", (int)retval); sleep(1); } return 0; }
运行结果:
thread Invalid argument
thread count 9
thread Invalid argument
thread count 8
thread Invalid argument
thread count 7
thread Invalid argument
thread count 6
thread Invalid argument
thread count 5
thread Invalid argument
thread count 4
thread Invalid argument
thread count 3
thread Invalid argument
thread count 2
thread Invalid argument
thread count 1
thread Invalid argument
thread count 0
thread Invalid argument
thread Invalid argument
如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!欢迎各位转载,但是未经作者本人同意,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
2017-01-10 美团HD(6)-添加搜索遮罩