### 一、使用方式
> pthread_t tid;
> pthread_create(&tid, NULL, thread_run,NULL);
> pthread_join(tid,NULL);
創建線程之后直接調用pthread_join方法就行了。
### 二、為什么要使用pthread_join()
? ? ?在很多情況下,主線程生成并起動了子線程,如果子線程里要進行大量的耗時的運算,主線程往往將于子線程之前結束,但是如果主線程處理完其他的事務后,需要用到子線程的處理結果,也就是主線程需要等待子線程執行完成之后再結束,這個時候就要用到pthread_join()方法了。
? ? ? 即pthread_join()的作用可以這樣理解:主線程等待子線程的終止。也就是在子線程調用了pthread_join()方法后面的代碼,只有等到子線程結束了才能執行。
### 三、代碼實驗
可以通過代碼來看看執行的效果,就知道了:
~~~
#include "stdafx.h"
#include <pthread.h>
#include <stdio.h>
#include <Windows.h>
#pragma comment(lib, "pthreadVC2.lib")
static int count = 0;
void* thread_run(void* parm)
{
for (int i=0;i<5;i++)
{
count++;
printf("The thread_run method count is = %d\n",count);
Sleep(1000);
}
return NULL;
}
int main()
{
pthread_t tid;
pthread_create(&tid, NULL, thread_run,NULL);
// 加入pthread_join后,主線程"main"會一直等待直到tid這個線程執行完畢自己才結束
// 一般項目中需要子線程計算后的值就需要加join方法
pthread_join(tid,NULL);
// 如果沒有join方法可以看看打印的順序
printf("The count is = %d\n",count);
getchar();
return 0;
}
~~~
加了pthread_join()方法的打印:

如果把里面的pthread_join()方法注釋掉的打印:

可以看得出來,如果沒有加pthread_join()方法,main線程里面直接就執行起走了,加了之后是等待線程執行了之后才執行的后面的代碼。
- 前言
- C++讀取配置文件
- 結構體內存對齊后所占內存空間大小的計算
- do{}while(0)的妙用
- Cocos2dx實現翻牌效果(CCScaleTo與CCOrbitCamera兩種方式)
- C++的error LNK2019: 無法解析的外部符號編譯錯誤
- Java使用JNI調用C++的完整流程
- strupr與strlwr函數的實現
- strcat函數實現
- Windows上VS使用pthread重溫經典多線程賣票(pthreads-w32-2-8-0-release.exe)(windows上使用pthread.h)
- pthread的pthread_join()函數理解實驗
- 順序存儲結構和鏈式存儲結構的選擇
- C語言冒泡排序
- VS看反匯編、寄存器、內存、堆棧調用來學習程序設計
- 快速排序
- C++的構造函數初始化列表
- fatal error C1083: 無法打開包括文件: “SDKDDKVer.h”: No such file or directory
- C++實現簡單的String類