Linux多线程编程之设置线程属性,设置线程分离属性

#include
#include
#include

//Linux多线程编程之设置线程属性,设置线程分离属性

/*
int pthread_join(pthread_t thread, void **retval);
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);
void pthread_exit(void *retval);
pthread_t pthread_self(void);
int pthread_detach(pthread_t thread);
*/

/*
主线程并不希望因为调用pthread_join而阻塞(因为还要继续处理之后到来的链接),这时可以在子线程中加入代码
pthread_detach(pthread_self())
*/

//线程1执行函数
void *pthread_1(void *arg)
{
    printf("pthrea 1 run...\n");
    int i =2;
    while(i--){
        printf("thread1 i =%d\n",i);
        sleep(1);
    }
    printf("pthread 1 exit\n");
    printf("-----------------\n");
    pthread_exit(NULL);//结束线程1
    return NULL;
}

//线程2执行函数
void *pthread_2(void *arg)
{
    printf("pthread 2 run..\n");

    sleep(3);
    printf("pthread 2 exit\n");
    printf("-----------------\n");
    pthread_exit(NULL);
    return NULL;
}

int main(void)
{
    printf("main thread tid = 0x%x\n",pthread_self());

    //创建子线程1
    pthread_t tid1;
    pthread_create(&tid1,NULL,pthread_1,NULL);
    //设置子线程1自动分离,回收8Kb资源
    pthread_detach(tid1);   

    //创建子线程2
    pthread_t tid2;
    pthread_create(&tid2,NULL,pthread_2,NULL);
    pthread_detach(tid2);

    sleep(5);
    printf("main pthread exit\n");
    pthread_exit(NULL);  //结束主线程    

    return 0;
}

/*
$ ./a.out
main thread tid = 0xb755b6c0
pthread 2 run..
pthrea 1 run...
thread1 i =1
thread1 i =0
pthread 1 exit
-----------------
pthread 2 exit
-----------------
*/






你可能感兴趣的:(C语言程序设计)