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

你可能感兴趣的:(pthread)