【Linux】分离线程
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
一、
为什么需要“分离线程”?
🖼️ 一图看懂分离线程生命周期
💻 实战:两种分离线程的写法
方法1:创建时直接分离(推荐)
方法2:运行时动态分离
一、
为什么需要“分离线程”?
想象一个场景:你的主线程创建了100个线程处理任务,但如果不做任何处理,每个线程结束后都会变成僵尸线程(保留退出状态,占用系统资源)。就像用完的快递盒不扔,堆满房间!
传统解决方式:
用pthread_join
手动回收(类似一个个拆快递盒),但主线程会被阻塞,无法继续干活。
更高效的方式:
分离线程(pthread_detach
)——线程结束后系统自动回收资源,无需等待!就像快递盒自动消失,主线程专注干正事。
🖼️ 一图看懂分离线程生命周期
(此处插入配图:线程状态流转图)
-
创建线程:
pthread_create
生成新线程 -
分离线程:调用
pthread_detach
或设置PTHREAD_CREATE_DETACHED
属性 -
线程结束:系统自动释放资源(无僵尸线程)
-
关键点:分离后不可
pthread_join
!(会返回错误码EINVAL
)
💻 实战:两种分离线程的写法
方法1:创建时直接分离(推荐)
#include <pthread.h>
#include <stdio.h>void* task(void* arg) {printf("子线程正在工作...\n");return NULL;
}int main() {pthread_t tid;pthread_attr_t attr;// 初始化线程属性pthread_attr_init(&attr);pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);// 创建分离线程pthread_create(&tid, &attr, task, NULL);pthread_attr_destroy(&attr);printf("主线程继续执行,无需等待子线程!\n");pthread_exit(NULL); // 防止主线程提前退出
}
方法2:运行时动态分离
#include <pthread.h>
#include <stdio.h>void* task(void* arg) {// 在线程内部分离自己pthread_detach(pthread_self());printf("子线程已分离,独立运行!\n");return NULL;
}int main() {pthread_t tid;pthread_create(&tid, NULL, task, NULL);// 主线程不调用pthread_joinsleep(1); // 确保子线程有时间执行return 0;
}