zoukankan      html  css  js  c++  java
  • 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 ~]#

  • 相关阅读:
    JAVA学习日报 8.2
    软件工程书籍《大道至简》读后感
    【CSAPP】第三章 程序的机器级表示
    【算法】KMP
    【经验总结】CodeBlocks使用mingw64
    【C++】指针和函数
    【C++】字符串处理
    【C++】自定义数据类型
    【C++】STL容器
    【C++】STL算法
  • 原文地址:https://www.cnblogs.com/Robotke1/p/3056264.html
Copyright © 2011-2022 走看看