pthread_join函数
来源:互联网 发布:外国男友的尺寸 知乎 编辑:程序博客网 时间:2024/04/20 10:07
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。
- pthread_join函数
- pthread_join()函数
- pthread_join函数
- pthread_join函数
- pthread_join函数
- pthread_join函数
- pthread_join函数
- pthread_join函数
- pthread_join函数
- pthread_join函数
- linux pthread_join函数详解
- 线程函数pthread_join
- pthread_join/pthread_exit函数
- linux pthread_join函数详解
- pthread_join()函数几点
- 多线程--pthread_join函数详解
- pthread_join()函数理解实验
- pthread_join()函数理解
- Intellij IDEA 中 .properties文件中文显示乱码问题的解决
- 深度学习Python mini_batch批处理训练
- OpenGL Windows下环境搭建
- iOS 【UIImagePickerController 系统方法详解】
- SIM800的CSQ值与RSSI关系
- pthread_join函数
- 【接口测试】:HttpURLConnection 发送post请求
- axure基本元件及属性
- (one day one problem)SPOJ
- Python基础学习-两小时上手Python
- 安卓开发 第十三篇 Android 中的测试
- 设置Tomcat的UTF-8编码
- Android Studio 新建 NDK Javah生成JNI头文件出现找不到类的错误
- Activity保存状态(二)