# VS配置pthread > POSIX线程(POSIX threads),简称Pthreads,是线程的POSIX标准。该标准定义了创建和操纵线程的一整套API。在类Unix操作系统(Unix、Linux、Mac OS X等)中,都使用Pthreads作为操作系统的线程。Windows操作系统也有其移植版pthreads-win32。 ## 下载源码 [资源地址](https://www.mirrorservice.org/sites/sourceware.org/pub/pthreads-win32/) 下载pthreads-w32-2-9-1-release.zip解压后得到三个文件夹。 - pthreads.2:pthreads.2 里面包含了pthreads 的源代码; - Pre-build.2:Pre-build.2 里面包含了pthreads for win32 的头文件和已编译好的库文件; - QueueUserAPCEx:QueueUserAPCEx 里面是一个alert的driver,编译需要DDK 。Windows Device Driver Kit (NTDDK.h) 需要额外单独安装。 一般情况下只需要使用Pre-build.2里面的文件即可。 ## 选择一:全局引用配置 1. 配置头文件 把include文件夹下的头文件拷贝到vs2017安装目录下,C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\include\ 2. 配置静态链接库 把lib文件夹下的静态库文件拷贝到vs2017安装目录下,D:\Program Files (x86)\Microsoft Visual Studio\2017\\Community\VC\Tools\MSVC\14.16.27023\lib 3. 配置动态链接库 Pre-built.2\dll\x86下的文件拷贝到C:\Windows\SysWOW64目录下 Pre-built.2\dll\x64下的文件拷贝到C:\Windows\System32目录下 ## 选择二:项目引用配置 在解决方案目录新建了个ThirdPartyLib目录,与项目目录同级,并把Pre-built.2下的三个文件夹拷过来。 右键项目 - 属性 - 配置属性 - C/C++ - 添加附加包含目录 - ThirdPartyLib\include ![image-20220527110318669](https://wangyuedong-img.oss-cn-beijing.aliyuncs.com/img/image-20220527110318669.png) 右键项目 - 属性 - 配置属性 - 链接器 - 添加Win32平台的附加库目录 - ThirdPartyLib\lib\x86 ![image-20220527111245325](https://wangyuedong-img.oss-cn-beijing.aliyuncs.com/img/image-20220527111245325.png) 右键项目 - 属性 - 配置属性 - 链接器 - 添加x64平台的附加库目录 - ThirtyPartyLib\lib\x64 ![image-20220527111654325](https://wangyuedong-img.oss-cn-beijing.aliyuncs.com/img/image-20220527111654325.png) 右键项目 - 属性 - 配置属性 - 调试 - 环境 - 添加Win32平台的附加库目录 - path=%path%;ThirdPartyLib\dll\x86 ![image-20220527112333044](https://wangyuedong-img.oss-cn-beijing.aliyuncs.com/img/image-20220527112333044.png) 右键项目 - 属性 - 配置属性 - 调试 - 环境 - 添加x64平台的附加库目录 - path=%path%;ThirdPartyLib\dll\x64 ![image-20220527112615683](https://wangyuedong-img.oss-cn-beijing.aliyuncs.com/img/image-20220527112615683.png) 这样头文件、静态库和动态库就针对单一项目完成配置了。 ## 测试多线程 ```c #include #include #include #include #pragma comment(lib, "pthreadVC2.lib") void *thread1(void *arg) { printf("wangyuedong.com\n"); return "thread1执行成功"; } void *thread2(void *arg) { printf("这是我的个人网站.\n"); return "thread2执行成功"; } int main(int argc, char *argv[]) { int res; pthread_t myThread1, myThread2; void *threadResult1; void *threadResult2; //创建线程 res = pthread_create(&myThread1, NULL, thread1, NULL); if (res != 0) { printf("子线程1创建失败.\n"); return EXIT_FAILURE; } res = pthread_create(&myThread2, NULL, thread2, NULL); if (res != 0) { printf("子线程2创建失败.\n"); return EXIT_FAILURE; } //线程执行完毕后获取线程数据 res = pthread_join(myThread1, &threadResult1); printf("%s\n", (char*)threadResult1); res = pthread_join(myThread2, &threadResult2); printf("%s\n", (char*)threadResult2); //主线程 printf("主线程执行完成.\n"); return 0; } ``` **“timespec”:“struct”类型重定义错误** ```c //方案一:修改预处理器配置 在预处理器定义中添加宏:HAVE_STRUCT_TIMESPEC //方案二:修改pthread.h文件 //添加宏 #define HAVE_STRUCT_TIMESPEC ``` 一顿操作之后发现还是运行错误,看来pthread还是适合Linux而不适合Windows。