pthread_join 望文生义害死人

来源:互联网 发布:阿里云qq客服 编辑:程序博客网 时间:2024/05/01 16:32
第一次当看到pthread_join(),我的字面理解是将一个thread加入到系统调度队列去,然后,有然后, 看代码就晕乎了。


其实pthread_join这个函数的作用是:
pthread_join使一个线程等待另一个线程结束。代码中如果没有pthread_join主线程会很快结束从而使整个进程结束,从而使创建的线程没有机会开始执行就结束了。加入pthread_join后,主线程会一直等待直到等待的线程结束自己才结束,使创建的线程有机会执行。


函数pthread_join用来等待一个线程的结束,线程间同步的操作。头文件 : #include <pthread.h>
函数定义: int pthread_join(pthread_t thread, void **retval);
描述 :pthread_join()函数,以阻塞的方式等待thread指定的线程结束。当函数返回时,被等待线程的资源被收回。如果线程已经结束,那么该函数会立即返回。并且thread指定的线程必须是joinable的。
参数 :thread: 线程标识符,即线程ID,标识唯一线程。retval: 用户定义的指针,用来存储被等待线程的返回值。
返回值 : 0代表成功。 失败,返回的则是错误号。


#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *thread(void *threadid)
{
int tid;
tid = (int)threadid;
printf("Hello World! It's me, thread #%d!/n", tid);
pthread_exit(NULL);
}
int main(void)
{
pthread_t id;
void *ret;
int i,retv;
int t=123;
retv=pthread_create(&id,NULL,(void *) thread,(void *)t);
if (retv!=0)
{
printf ("Create pthread error!/n");
return 1;
}
for (i=0;i<3;i++)
printf("This is the main process./n");
pthread_join(id,&ret);
printf("The thread return value is%d/n",(int)ret);
return 0;
}
0 0
原创粉丝点击