vs2019 c语言配置pthreads多线程

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, &param);
ret_thrd2 = pthread_create(&thread2, NULL, print_message_function, &param);

// 线程创建成功,返回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

 

 

posted @ 2020-10-29 10:23  maycpou  阅读(3343)  评论(0编辑  收藏  举报