Linux中以PTHREAD_CREATE_DETACHED属性创建线程

     在线程创建时将其属性设为分离状态(detached),也可在线程创建后将其属性设为分离的(detached)。

这里使用在创建时指定线程为PTHREAD_CREATE_DETACHED属性。

一、实例

#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_attr_t attr;

    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);  // 设置分离属性

    pthread_create(&tid, &attr, (void*)thread1, NULL);
    pthread_attr_destroy(&attr);

    sleep(1);
    printf("Leave main thread!\n");

    return 0;
}

程序输出:

[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 ~]#

转载于:https://www.cnblogs.com/Robotke1/archive/2013/05/03/3056264.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值