POSIX Threads for Win32項目,專門為win32開發了一個pthread的lib,利用這個項目可以很友善的在win32下實作pthread的應用。
一,下載下傳
POSIX Threads for Win32目前可以下載下傳到的最新版本是2.9.1 ,
下載下傳位址:https://sourceforge.net/projects/pthreads4w/files/?source=navbar
将下載下傳到的zip解壓之後,會得到三個目錄:其中,Pre-built.2中是已經編譯好的lib以及dll,同時包含了一些必要的頭檔案。
二 .配置
将其中的include檔案夾和lib檔案夾 copy到VC的安裝目錄下,例如,我的是vs2013的環境,預設安裝,則,
需要copy到:Program Files (x86)\Microsoft Visual Studio 12.0\VC
把dll下的x64檔案夾下的兩個檔案,即pthreadGC2.dll與pthreadVC2.dll拷貝到C:\Windows\System32下(用于64位程式的運作)
把dll下的x86檔案夾下的五個檔案,拷貝到C:\Windows\SysWOW64下(用于32位程式的運作),注意一下,千萬不能将這些檔案拷貝反位置,否則,程式運作時會提示說找不到對應的dll檔案。
三.使用
在程式設計的時候,引入pthreadVC2.lib即可:
#pragma comment(lib, "pthreadVC2.lib")
調試個例子,(代碼來自網絡)
#include <stdio.h>
#include <pthread.h>
#include <assert.h>
#pragma comment(lib, "pthreadVC2.lib")
typedef struct _qsort_parm
{
int *array;
int low;
int high;
} qsort_parm_t;
/*分段*/
int partition(int *array, int low, int high)
{
int pivot = *(array + low); //first element
while (low < high)
{
while (low < high && array[high] >= pivot)
{
high--;
}
*(array + low) = *(array + high);
while (low < high && array[low] <= pivot)
{
low++;
}
*(array + high) = *(array + low);
}
*(array + low) = pivot;
return low;
}
/*線程執行函數*/
void* quicksort_worker(void *parm)
{
pthread_t corpid;
qsort_parm_t *iparm = (qsort_parm_t *)parm;
int keypos = 0;
qsort_parm_t qparm;
void *ret;
if (iparm->low < iparm->high)
{
/*分段*/
keypos = partition(iparm->array, iparm->low, iparm->high);
qparm.array = iparm->array;
qparm.low = iparm->low;
qparm.high = keypos - 1;
/*建立子線程處理前半段*/
pthread_create(&corpid, NULL, quicksort_worker, &qparm);
iparm->low = keypos + 1;
/*本線程處理後半段*/
quicksort_worker(iparm);
/*等待子線程結束*/
pthread_join(corpid, &ret);
}
return NULL;
}
void* Function_t(void* Param)
{
printf("我是線程! ");
pthread_t myid = pthread_self();
printf("線程ID=%d ", myid);
return NULL;
}
void quicksort_multithread(int *pA, int low, int high)
{
qsort_parm_t qparm;
qparm.array = pA;
qparm.low = low;
qparm.high = high;
quicksort_worker(&qparm);
}
int main(void){
int array[20] = { 9, 8, 0, 1, 4, 7, 6, 2, 3, 5, 19, 11, 18, 16, 10, 22, 38, 45, 14, 21 };
int i = 0;
quicksort_multithread(array, 0, 19);
for (i = 0; i < 20; i++)
{ printf("%d ", array[i]); }
getchar();
return 0;
}