Linux中pthread_detach()線程注意


一、創建分離線程

有兩種方式創建分離線程:

(1)在線程創建時將其屬性設為分離狀態(detached);

(2)在線程創建后將其屬性設為分離的(detached)。

二、分離線程的作用

由系統來回收線程所占用資源。

三、實例

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/types.h>
#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_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()),從而導致進程及其所有線程(包括分離線程)結束運行。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM