一、创建分离线程
有两种方式创建分离线程:
(1)在线程创建时将其属性设为分离状态(detached);
(2)在线程创建后将其属性设为分离的(detached)。
二、分离线程的作用
由系统来回收线程所占用资源。
三、实例
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/types.h>
#include <dirent.h>
#include <pthread.h>
#include <errno.h>
#include <signal.h>
#include <time.h>
void* thread1(void *arg)
{
while (1)
{
usleep(100 * 1000);
printf("thread1 running...!\n");
}
printf("Leave thread1!\n");
return NULL;
}
int main(int argc, char** argv)
{
pthread_t tid;
pthread_create(&tid, NULL, (void*)thread1, NULL);
pthread_detach(tid); // 使线程处于分离状态
sleep(1);
printf("Leave main thread!\n");
return 0;
}
这里的thread1线程是一个“死循环”,thread1线程又是“分离线程”。
那么会不会主线程退出之后,thread1线程一直在运行呢?
程序输出:
[root@robot ~]# gcc thread_detach.c -lpthread
[root@robot ~]# ./a.out
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
Leave main thread!
[root@robot ~]#
可以看到在主线程退出之后,thread1线程也退出了。
注意:“分离线程”并不是“分离”了之后跟主线程没有一点关系,主线程退出了,“分离线程”还是一样退出。只是“分离线程”的资源是有系统回收的。
四、结论
在进程主函数(main())中调用pthread_exit(),只会使主函数所在的线程(可以说是进程的主线程)退出;
而如果是return,编译器将使其调用进程退出的代码(如_exit()),从而导致进程及其所有线程(包括分离线程)结束运行。