zoukankan      html  css  js  c++  java
  • 线程分离

    int pthread_detach(pthread_t th);

    pthread_detach函数使线程处于被分离状态。

    如果不等待一个线程,同时对线程的返回值不感兴趣,可以设置这个线程为分离状态,让系统在线程退出的时候自动回收它所占用的资源。

    一个线程不能自己调用pthread_detach改变自己被分离状态,只能由其他线程调用pthread_detach。

    /***
    detach.c
    ***/
    #include<stdio.h>
    #include<pthread.h>
    #include<errno.h>
    #include<string.h>
    #include<stdlib.h>
    
    void * func(void *arg)
    {
        int i;
        for(; i < 5; i++)
        {
            printf("func run %d
    ",i);
            sleep(1);
        }
        int *p = (int*)malloc(sizeof(int));
        * p = 11;
        return p;
    }
    
    int main()
    {
        pthread_t t1;
        
        pthread_attr_t attr;
        pthread_attr_init(&attr);
        pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
    
        int err = pthread_create(&t1,&attr,func,NULL);
        if( 0 != err)
        {
            printf("thread_create failled : %s
    ",strerror(errno));
        }
        else
        {
            printf("thread_create success
    ");
        }
        pthread_attr_destroy(&attr);
    
        pthread_join(t1,NULL);
        printf("main thread exit
    ");
    
        return EXIT_SUCCESS;
    }

    pthread_attr_t 就是我们要传入的参数的结构体,一般声明的步骤:

    1. 声明一个pthread_attr_t的对象
    2. 函数pthread_attr_init初始化attr结构。
    3. 设置线程一些属性,比如pthread_attr_setdetachstate函数就是设置该线程创建的时候为正常状态还是分离状态。
    4. 函数pthread_attr_desory释放attr内存空间。

    pthread_attr_setdetachstate 把线程属性设置为下面两个合法值之一:

    说明

    PTHREAD_CREATE_DETACHED

    设置线程为分离状态

    PTHREAD_CREATE_JOINABLE

    设置线程为正常状态

    运行结果:

    exbot@ubuntu:~/wangqinghe/thread/20190729$ gcc detach.c -o detach -lpthread

    exbot@ubuntu:~/wangqinghe/thread/20190729$ ./detach

    thread_create success

    main thread exit

    因为线程是个分离状态,所以pthread_join挂起会失效,主线程很快就运行结束,程序也就结束了,创建的线程还没来得及运行。

  • 相关阅读:
    jquery 获取 input type radio checked的元素
    各种js验证规则
    centos7 vsftp xftp 解决无法显示远程文件夹,可登陆
    js浮点运算精度丢失的解决办法
    ThinkPHP 改装后的分页类
    亚马逊AWS开启之路
    上慕课从这里开始 (www-mooc.com)
    iptables httpd.conf详解
    微信带链接的文本消息推送
    IE8不支持响应式设计解决方法
  • 原文地址:https://www.cnblogs.com/wanghao-boke/p/11264642.html
Copyright © 2011-2022 走看看