VS2019配置pthread多线程

在VS里用MS编译器不能直接调用pthread库,需要先自行下载该库: http://sourceware.org/pub/pthreads-win32/pthreads-w32-2-9-1-release.zip 解压后用的到的只有Pre-built.2文件夹下的文件。

配置

如下图分别配置三大项:

  • 包含目录–>…\pthreads-w32-2-9-1-release\Pre-built.2\include
  • 库目录–>…\pthreads-w32-2-9-1-release\Pre-built.2\lib\x86
  • 附加依赖项–>pthreadVC2.lib

  • 如果代码运行报错:“timespec”;”struct”类型重定义。 解决方法:在pthread.h在第35行加入如下代码:
#define HAVE_STRUCT_TIMESPEC

或者在项目属性->C\C++->预处理器->预处理器定义添加HAVE_STRUCT_TIMESPEC。

  • 如果代码运行报错:找不到pthreadVC2.dll。 解决方法:将pthreadVC2.dll拷贝到项目的Debug目录下

示例代码

#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <pthread.h> //使用多线程时需要添加<pthread.h>这个头文件

int s = 0;

void* transmit(void* args) {
	char* name = (char*)args;
	for (int i = 0; i < 1000; i++) {
		s++;
		printf("----------%s : s = %d----------\n", name, s);
		Sleep(1000);
	}
}

void* receive(void* args) {
	char* name = (char*)args;
	while (1)
	{
		printf("%s : s = %d\n", name, s);
		Sleep(100);
	}
}

int main() {
	pthread_t tx, rx;

	pthread_create(&tx, NULL, transmit, "TX");
	pthread_create(&rx, NULL, receive, "RX");

	pthread_join(tx, NULL);
	pthread_join(rx, NULL);

	return 0;
}

参考

https://www.cnblogs.com/maycpou/p/13895295.html https://zhuanlan.zhihu.com/p/97418361