一、创建分离线程
有两种方式创建分离线程:
(1)在线程创建时将其属性设为分离状态(detached);
(2)在线程创建后将其属性设为分离的(detached)。
二、分离线程的作用
由系统来回收线程所占用资源。
三、实例
#include#gcc a.c -lpthread
#./a.out
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
Leave main thread!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
可以看出main线程退出后,thread_1并没有退出。
$ cat a.c
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
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;
}
$ ./a.out
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
Leave main thread!
可以看出main线程return后,子线程也退出了。
如果把pthread_deteach改为pthread_join,因为子线程是while(1)所有主线程也不会退出。
linjuntao@linjuntao:~/work/mt8516-p1v2/build/tmp/deploy/images/aud8516p1v2-slc-bluez$ cat a.c
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
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); // 使线程处于分离状态
pthread_join(tid,NULL); // 使线程处于分离状态
sleep(1);
printf("Leave main thread!\n");
return 0;
}
linjuntao@linjuntao:~/work/mt8516-p1v2/build/tmp/deploy/images/aud8516p1v2-slc-bluez$ ./a.out
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
^
这可以在main中使用pthread_cancel,明确退出子线程。