线程相关函数(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

 



如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!欢迎各位转载,但是未经作者本人同意,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。
posted @   夜行过客  阅读(2254)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
历史上的今天:
2017-01-10 美团HD(6)-添加搜索遮罩
点击右上角即可分享
微信分享提示