線程相關函數(3)-pthread_detach()將某個線程設成分離態


 

#include <pthread.h>
int pthread_detach(pthread_t tid);


pthread_t tid:  分離線程的tid
返回值:成功返回0,失敗返回錯誤號。

一般情況下,線程終止后,其終止狀態一直保留到其它線程調用pthread_join獲取它的狀態為止。但是線程也可以被置為detach狀態,這樣的線程一旦終止就立刻回收它占用的所有資源,而不保留終止狀態。不能對一個已經處於detach狀態的線程調用pthread_join,這樣的調用將返回EINVAL。如果已經對一個線程調用了pthread_detach就不能再調用pthread_join了。
通常情況下,若創建一個線程不關心它的返回值,也不想使用pthread_join來回收(調用pthread_join的進程會阻塞),就可以使用pthread_detach,將該線程的狀態設置為分離態,使線程結束后,立即被系統回收。

示例代碼:

#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

void *thr_fn(void *arg)
{
    int n = 10;
    while(n--) {
        printf("thread count %d\n", n);
        sleep(1);
    }
    return (void *)1;
}


int main()
{    
    
    pthread_t tid;
    void *retval;
    int err;

    pthread_create(&tid, NULL, thr_fn, NULL);
    pthread_detach(tid);
        
    while(1) {
        err = pthread_join(tid, &retval);
        if (err != 0)
            fprintf(stderr, "thread %s\n", strerror(err));
        else 
            fprintf(stderr, "thread exit code %d\n", (int)retval);
        sleep(1);
    }
    return 0;
}

運行結果:

thread Invalid argument
thread count 9
thread Invalid argument
thread count 8
thread Invalid argument
thread count 7
thread Invalid argument
thread count 6
thread Invalid argument
thread count 5
thread Invalid argument
thread count 4
thread Invalid argument
thread count 3
thread Invalid argument
thread count 2
thread Invalid argument
thread count 1
thread Invalid argument
thread count 0
thread Invalid argument
thread Invalid argument

 


免責聲明!

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



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