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

    线程分离的作用:当主线程与新线程无关时,主线程无需等待新线程的结束。

    1、进程属性初始化

    pthread_attr_t pth_attr; 
    pthread_attr_init(&pth_attr);
    2、进程分离属性设置。

    pthread_attr_setdetachstate(&pth_attr,PTHREAD_CREATE_DETACHED);

    3、进程创建。

    4、进程属性资源回收。

    pthread_attr_destroy(&pth_attr);

    #include<stdio.h>
    #include<string.h>
    #include<unistd.h>
    #include<stdlib.h>
    #include<pthread.h>
    
    void *thread_func(void *arg);
    #define handle_error(msg) 
        do { perror(msg); exit(EXIT_FAILURE);} while(0)
    char message[] = "hello Ruanchao!";
    int finish=0;
    int main() {
        int res;
        pthread_t thread;
        pthread_attr_t pth_attr;
        
        res = pthread_attr_init(&pth_attr);
        if (res != 0) 
            handle_error("pthread initial is failed!");
        res = pthread_attr_setdetachstate(&pth_attr,PTHREAD_CREATE_DETACHED);
        if(res != 0)
            handle_error("pthread set attr failed!");
        res = pthread_create(&thread,&pth_attr,thread_func,(void *)message);
        if(res != 0)
            handle_error("thread creation is failed!");
        (void)pthread_attr_destroy(&pth_attr);
        while(!finish) {
            printf("Waiting for thread to end!
    ");
            sleep(1);
        }
        printf("thread were finished!
    ");
        exit("EXIT_FAILURE");
    }
    void *thread_func(void *arg){
        printf("thread_func is running,argument is %s
    ",(char *)arg);
        sleep(5);
        finish = 1;
        pthread_exit(NULL);
    }
  • 相关阅读:
    float保留指定位数的小数
    springmvc中拦截器的使用
    springmvc文件上传
    spring注入
    mybatis动态代理
    2017《JAVA技术》预备作业02 计科1502 郎春雨
    2017《JAVA技术》预备作业01 计科1502 郎春雨
    字符串占位符的使用
    Pyenv虚拟环境的创建(虚拟机)
    Git的基本使用
  • 原文地址:https://www.cnblogs.com/farbeyond/p/4488758.html
Copyright © 2011-2022 走看看