码迷,mamicode.com
首页 > 编程语言 > 详细

线程分离

时间:2015-05-08 21:53:33      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

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

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!\n");
        sleep(1);
    }
    printf("thread were finished!\n");
    exit("EXIT_FAILURE");
}
void *thread_func(void *arg){
    printf("thread_func is running,argument is %s\n",(char *)arg);
    sleep(5);
    finish = 1;
    pthread_exit(NULL);
}

 

线程分离

标签:

原文地址:http://www.cnblogs.com/farbeyond/p/4488758.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!