1.下載pthreads-w32-2-9-1-release.zip文件,解壓
2. 項目屬性=》=》vc++目錄=》包含目錄=》添加 xxx\pthreads-w32-2-9-1-release\Pre-built.2\include
3.項目屬性=》=》vc++目錄=》庫目錄=》添加xxx\pthreads-w32-2-9-1-release\Pre-built.2\lib\x64
4.項目屬性=》=》鏈接器=》輸入=》附加依賴項=》添加pthreadVC2.lib
5.測試代碼:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
void* print_message_function(void* ptr);
struct node_ {
int index;
int name;
}node;
int main()
{
int tmp1, tmp2;
void* retval;
pthread_t thread1, thread2;
char* message1 = "thread1";
char* message2 = "thread2";
node_ param;
param.index = 5;
param.name = 8888;
int ret_thrd1, ret_thrd2;
ret_thrd1 = pthread_create(&thread1, NULL, print_message_function, ¶m);
ret_thrd2 = pthread_create(&thread2, NULL, print_message_function, ¶m);
// 線程創建成功,返回0,失敗返回失敗號
if (ret_thrd1 != 0) {
printf("線程1創建失敗\n");
}
else {
printf("線程1創建成功\n");
}
if (ret_thrd2 != 0) {
printf("線程2創建失敗\n");
}
else {
printf("線程2創建成功\n");
}
//同樣,pthread_join的返回值成功為0
tmp1 = pthread_join(thread1, &retval);
printf("thread1 return value(retval) is %d\n", (int)retval);
printf("thread1 return value(tmp) is %d\n", tmp1);
if (tmp1 != 0) {
printf("cannot join with thread1\n");
}
printf("thread1 end\n");
tmp2 = pthread_join(thread1, &retval);
printf("thread2 return value(retval) is %d\n", (int)retval);
printf("thread2 return value(tmp) is %d\n", tmp1);
if (tmp2 != 0) {
printf("cannot join with thread2\n");
}
printf("thread2 end\n");
}
void* print_message_function(void* ptr) {
node_* pc = (node_*)ptr;
int i = 0;
for (i; i < 5; i++) {
printf("%d:%d\n", pc->name, i);
}
return NULL;
}
6.如果代碼運行報錯:找不到pthreadVC2.dll。解決方法:將pthreadVC2.dll拷貝到項目的Debug目錄下
7.如果代碼運行報錯:“timespec”;”struct”類型重定義。解決方法:在pthread.h在第35行加入如下代碼:#define HAVE_STRUCT_TIMESPEC