Chinaunix首页 | 论坛 | 博客
  • 博客访问: 891979
  • 博文数量: 299
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2493
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-21 10:07
个人简介

Linux后台服务器编程。

文章分类

全部博文(299)

文章存档

2015年(2)

2014年(297)

分类: LINUX

2014-10-24 21:09:38

一、创建分离线程

有两种方式创建分离线程:

(1)在线程创建时将其属性设为分离状态(detached);

(2)在线程创建后将其属性设为分离的(detached)。

二、分离线程的作用

由系统来回收线程所占用资源。

三、实例

复制代码
#include  #include <string.h> #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;
}
复制代码


     这里的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()),从而导致进程及其所有线程(包括分离线程)结束运行。

阅读(3959) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~