您的位置:首页 > 运维架构 > Linux

Linux中以PTHREAD_CREATE_DETACHED属性创建线程

2013-05-03 11:05 781 查看
在线程创建时将其属性设为分离状态(detached),也可在线程创建后将其属性设为分离的(detached)。

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

[b]一、实例[/b]

#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 ~]#
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: