Linux多线程05-线程的分离

pthread_detach

描述:

pthread_detach()函数将由thread标识的线程标记为已分离。当一个分离的线程终止时,它的资源会自动释放回系统,而不需要另一个线程与已终止的线程加入。尝试分离一个已经分离的线程会导致未指定的行为。

#include <pthread.h>
int pthread_detach(pthread_t thread);
    功能: 分离一个线程, 被分离的线程在终止时自动释放资源返回给系统
        1.不能多次分离, 会产生不可预料的行为
        2.不能去连接一个已经分离的线程, 会报错
    参数: 需要分离的线程ID
    返回: 成功-0 , 失败-错误号

Compile and link with -pthread.

代码示例

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

void* callback(void* arg){
    printf("child thread id: %ld\n",pthread_self());

    return NULL;
}

int main(){
    pthread_t tid;
    int ret = pthread_create(&tid, NULL, callback, NULL);
    if(ret!=0){
        char* errstr = strerror(ret);
        printf("error_create: %s\n",errstr);
    }
    
    //输出主线程和子线程ID
    printf("tid: %ld, main thread id: %ld\n",tid,pthread_self());

    //设置子线程分离, 子线程分离后, 子线程结束时对应的资源就不需要主线程释放
    ret = pthread_detach(tid);
    if(ret!=0){
        char* errstr = strerror(ret);
        printf("error_detach: %s\n",errstr);
    }

    //分离线程后尝试再释放
    ret = pthread_join(tid, NULL);
    if(ret!=0){
        char* errstr = strerror(ret);
        printf("error_join: %s\n",errstr); //报错, 非法参数
    }

    pthread_exit(NULL);

    return 0;
}

运行结果

tid: 140639219562240, main thread id: 140639227950912
error_join: Invalid argument
child thread id: 140639219562240
posted @ 2023-06-26 08:53  言叶以上  阅读(27)  评论(0编辑  收藏  举报