使用pthread的好處在於對於跨平台的程序,無需重寫線程部分。目前跨平台的線程庫還有,Boost.Thread, Intel TBB里的線程類(與Boost.Thread接口幾乎相同),ACE里的活動對象類,ICE里的線程類。
PMVS源碼在多線程使用pthread,這個庫一般用於linux下,要在win7 64bit下使用也挺簡單:
1. 下載pthreads-w32-2-8-0-release.exe
下載地址:ftp://sourceware.org/pub/pthreads-win32
2. 安裝pthreads-w32-2-8-0-release.exe
雙擊pthreads-w32-2-8-0-release.exe,點擊Browse選擇安裝到的目錄,然后點擊Extract解壓,完成后點擊Done。
之后會在安裝目錄看到有三個文件夾Pre-built.2、pthreads.2、QueueUserAPCEx. 第一個是生成庫(頭文件和庫文件那些),第二個是源碼,第三個不清楚,像是測試程序。
將Pre-built.2文件夾下的include和lib文件夾里的文件復制到VS2008對應的include和lib目錄,例如C:\Program Files(X86)\Microsoft Visual Studio 9.0\VC\include和C:\Program Files(X86)\Microsoft VisualStudio 9.0\VC\lib.
3. 編寫測試程序
#include<stdio.h>
#include<pthread.h>
#include<Windows.h>
#pragma comment(lib, "pthreadVC2.lib") //必須加上這句
void*Function_t(void* Param)
{
pthread_t myid = pthread_self();
while(1)
{
printf("線程ID=%d \n", myid);
Sleep(4000);
}
return NULL;
}
int main()
{
pthread_t pid;
pthread_create(&pid, NULL, Function_t,NULL);
while (1)
{
printf("in fatherprocess!\n");
Sleep(2000);
}
getchar();
return 1;
}
運行過程中出現缺少“pthreadVC2.dll”,這時候需要將.lib中對應的文件拷貝到windows的系統文件夾下,對於64bit,拷貝位置為“C:\Windows\SysWOW64”
