码迷,mamicode.com
首页 > 其他好文 > 详细

pthread_join/pthread_exit的用法解析

时间:2014-12-16 17:09:58      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:function   通信   存储   指针   实例   

官方说法:

函数pthread_join用来等待一个线程的结束。函数原型为:

  extern int pthread_join __P ((pthread_t __th, void **__thread_return));

  第一个参数为被等待的线程标识符,第二个参数为一个用户定义的指针,它可以用来存储被等待线程的返回值。这个函数是一个线程阻塞的函数,调用它的线程将一直等待到被等待的线程结束为止,当函数返回时,被等待线程的资源被收回。一个线程的结束有两种途径,一种是象我们上面的例子一样,函数结束了,调用它的线程也就结束了;

另一种方式是通过函数pthread_exit来实现。它的函数原型为:

  extern void pthread_exit __P ((void *__retval)) __attribute__ ((__noreturn__));

  唯一的参数是函数的返回代码,只要pthread_exit中的参数retval不是NULL,这个值将被传递给 thread_return。最后要说明的是,一个线程不能被多个线程等待,否则第一个接收到信号的线程成功返回,其余调用pthread_join的线程则返回错误代码ESRCH。


上面说的有点乱,看不懂的看这里:

pthread_join用于等待一个线程的结束,也就是主线程中要是加了这段代码,就会在加代码的位置卡主,直到这个线程执行完毕才往下走。

pthread_exit用于强制退出一个线程(非执行完毕退出),一般用于线程内部。


结合用法:

一般都是pthread_exit在线程内退出,然后返回一个值。这个时候就跳到主线程的pthread_join了(因为一直在等你结束),这个返回值会直接送到pthread_join,实现了主与分线程的通信。


注意事项:

这个线程退出的返回值的格式是void*,无论是什么格式都要强转成void*才能返回出来主线程,而这个时候pthread_join就去接这个值,我们传进去一个void*的地址也就是&(void*),传地址进去接值是接口类函数常用的做法,有同样效果的做法是引用&,但是这个做法一来值容易被误改,二来不规范,所以定义一个类型然后把地址传进去修改value。回到题目,这里返回的void*可以直接用,强转成其他类型就直接能用了,甚至能强转成int。


实例如下:

                       
/* example.c*/

#include <stdio.h>

#include <pthread.h>

void thread1(char s[])
{ 
        printf("This is a pthread1.\n");
        printf("%s\n",s);
        pthread_exit((void*)"the first return!");  //结束线程,返回一个值。
}
void thread2(char s[])
{
        printf("This is a pthread2.\n");
        printf("%s\n",s);
        pthread_exit((void*)"the second return!");
}

/**************main function ****************/

int main(void)


{
        pthread_t id1,id2;
        void *a1,*a2;
        int i,ret1,ret2;
        char s1[]="This is first thread!";
        char s2[]="This is second thread!";
        ret1=pthread_create(&id1,NULL,(void *) thread1,s1);

        ret2=pthread_create(&id2,NULL,(void *) thread2,s2);

        if(ret1!=0){
                printf ("Create pthread1 error!\n");
                exit (1);
        }
        pthread_join(id1,&a1);

        printf("%s\n",(char*)a1);

        if(ret2!=0){
                printf ("Create pthread2 error!\n");
                exit (1);
        }
        printf("This is the  main process.\n");
        pthread_join(id2,&a2);
        printf("%s\n",(char*)a2);
        return (0);

}  

运行结果: 
[****@XD**** c]$ ./example 
This is a pthread1. 
This is first thread! 

the first return!
This is the main process. 
This is a pthread2. 
This is second thread! 

the second return!

pthread_join/pthread_exit的用法解析

标签:function   通信   存储   指针   实例   

原文地址:http://blog.csdn.net/modiziri/article/details/41961595

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