zoukankan      html  css  js  c++  java
  • 线程相关函数(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);
            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
    ", strerror(err));
            else 
                fprintf(stderr, "thread exit code %d
    ", (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

  • 相关阅读:
    Docker 入门指南——Dockerfile 指令
    这个断点可以帮你检查布局约束
    个推你应该这样用的
    网易云直播SDK使用总结
    当微信和支付宝遇上友盟
    环信SDK 头像、昵称、表情自定义和群聊设置的实现 二(附源码)
    环信SDK 头像、昵称、表情自定义和群聊设置的实现 一(附源码)
    事件分发机制
    常用开发技巧系列(一)
    iOS RunTime你知道了总得用一下
  • 原文地址:https://www.cnblogs.com/yongdaimi/p/8258454.html
Copyright © 2011-2022 走看看