pthread_join函数
1、 函数功能:
在某个函数func中调用该函数的话,意思是等待pthread_join中的线程执行完后才会往下执行。
Void func()
{
…
pthread_join(th,NULL);
…
}
寓意是:当func函数执行到pthread_join时,会以阻塞方式等待线程th执行完,释放资源后往下执行。可能后边会使用到th的结果。
2、 函数原型:
int pthread_join(pthread_t th, void **returnVla)
其中th是一个线程的id;returnVla是被等待线程的返回值;
3、 代码例子
(1)在main函数中调用了pthread_join函数,那么当主线程执行到pthread_join时会以阻塞方式停下来,等待pthread_join中的线程执行完毕后自己再往下执行print和getchar。
#include<pthread.h>
#include<stdio.h>
#include<Windows.h>
#pragmacomment(lib,"pthreadVC2.lib")
staticintcount=0;
void*thread_run(void*parm)
{
for(inti=0;i<5;i++)
{
count++;
printf("The thread_run method count is = %d\n",count);
Sleep(1000);
}
returnNULL;
}
intmain()
{
pthread_ttid;
pthread_create(&tid,NULL,thread_run,NULL);
// 加入pthread_join后,主线程"main"会一直等待直到tid这个线程执行完毕自己往下执行 printf和getchar
// 一般项目中需要子线程计算后的值就需要加join方法
pthread_join(tid,NULL);
printf("Thecount is = %d\n",count);
getchar();
return0;
}
执行到pthread_join后当前函数(main)会以阻塞方式停下来,等待pthread_join指定的线程(tid)结束后再在往下执行(print和getchar);
(2)在main函数中没有调用pthread_join函数,此时主线程(main函数)和子线程(tid)同时竞争CPU执行。由于子线程中的计算复杂首先执行了printf,getchar。
#include<pthread.h>
#include<stdio.h>
#include<Windows.h>
#pragmacomment(lib,"pthreadVC2.lib")
staticintcount=0;
void*thread_run(void*parm)
{
for(inti=0;i<5;i++)
{
count++;
printf("The thread_run method count is = %d\n",count);
Sleep(1000);
}
returnNULL;
}
intmain()
{
pthread_ttid;
pthread_create(&tid,NULL,thread_run,NULL);
// 加入pthread_join后,主线程"main"会一直等待直到tid这个线程执行完毕自己往下执行 printf和getchar
// 一般项目中需要子线程计算后的值就需要加join方法
// pthread_join(tid, NULL);
printf("Thecount is = %d\n",count);
getchar();
return0;
}
这里有两个线程:主线程(main函数)和子线程(tid)同时执行,抢占CPU,但是由于子线程的计算比较耗时,所以会先执行print和getchar。