VS2015 添加 pthread 库


在 VS2015 中使用 POSIX 线程模型

点我下载 pthread 库

1. 安装 pthread 库

1.1 头文件

  1. 将下载的 pthread 库压缩包解压得到 Pre-built.2pthreads.2QueueUserAPCEx三个目录

  2. 使用文本编辑器打开 Pre-built.2/include/pthread.h,添加定义 #define HAVE_STRUCT_TIMESPEC,如下所示

    #if !defined( PTHREAD_H )
    #define PTHREAD_H
    #define HAVE_STRUCT_TIMESPEC // 避免重复定义 struct timespec
    
  3. Pre-built.2/include 中的三个头文件复制到 VS2015 的 %InstallRoot%/VC/include

1.2 静态库

  1. Pre-built.2/lib/x86 中的三个 lib 文件放到 VS2015 的 %InstallRoot%/VC/lib

  2. Pre-built.2/lib/x64 中的一个 lib 文件放到 VS2015 的 %InstallRoot%/VC/lib/amd64 或者 %InstallRoot%/VC/lib/x64

1.3 动态库

  1. Pre-built.2\dll\x86 中的五个 dll 文件放到 C:\Windows\SysWOW64

  2. Pre-built.2\dll\x64 中的两个 dll 文件放到 C:\Windows\System32

嗯,对,没错,就是 86 对 64,64 对 86,我没写错!

2. 示例程序

#include 
#include 

#ifdef _WIN32
#pragma comment(lib,"pthreadVC2.lib")
#endif // _WIN32

void * thread_entry(void* argv)
{
	pthread_t  self = pthread_self();
	printf("I am %lld\n", (long long)&self);
	return 0;
}

int main(int argc, char* argv[])
{
	pthread_t thread1;
	pthread_t thread2;
	pthread_create(&thread1, 0, thread_entry, 0);
	pthread_create(&thread2, 0, thread_entry, 0);
	pthread_join(thread1, 0);
	pthread_join(thread2, 0);
	return 0;
}