1.下载pthreads-w32-2-9-1-release.zip文件,解压
2. 项目属性=》=》vc++目录=》包含目录=》添加 xxxpthreads-w32-2-9-1-releasePre-built.2include
3.项目属性=》=》vc++目录=》库目录=》添加xxxpthreads-w32-2-9-1-releasePre-built.2libx64
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创建失败
");
}
else {
printf("线程1创建成功
");
}
if (ret_thrd2 != 0) {
printf("线程2创建失败
");
}
else {
printf("线程2创建成功
");
}
//同样,pthread_join的返回值成功为0
tmp1 = pthread_join(thread1, &retval);
printf("thread1 return value(retval) is %d
", (int)retval);
printf("thread1 return value(tmp) is %d
", tmp1);
if (tmp1 != 0) {
printf("cannot join with thread1
");
}
printf("thread1 end
");
tmp2 = pthread_join(thread1, &retval);
printf("thread2 return value(retval) is %d
", (int)retval);
printf("thread2 return value(tmp) is %d
", tmp1);
if (tmp2 != 0) {
printf("cannot join with thread2
");
}
printf("thread2 end
");
}
void* print_message_function(void* ptr) {
node_* pc = (node_*)ptr;
int i = 0;
for (i; i < 5; i++) {
printf("%d:%d
", pc->name, i);
}
return NULL;
}
6.如果代码运行报错:找不到pthreadVC2.dll。解决方法:将pthreadVC2.dll拷贝到项目的Debug目录下
7.如果代码运行报错:“timespec”;”struct”类型重定义。解决方法:在pthread.h在第35行加入如下代码:#define HAVE_STRUCT_TIMESPEC