vs配置pthread多线程(附pthread多线程测试)(解决error C2011: “timespec”:“struct”类型重定义)

一、首先要配置环境,载包。linux

     

  咱们选第二个zip,第一个是给linux系统的啦,不过老师好像说linux系统自己就支持多线程(应该是在linux里能够经过指令直接下载,正常状况下不须要再载安装包放入虚拟机里)。web

  打开后找到Pre-built.2>include,能够看见三个头文件,这是三个咱们须要去移动到vs里的头文件,先留着。多线程

 

二、用记事本或者编译器打开pthread.h文件函数

     这是本来文件的代码:测试

     

 

     咱们须要在35行的位置添加下面一条代码:ui

         #define HAVE_STRUCT_TINMESPECthis

 

           

 

  为何要在将文件移动到vs文件夹内以前修改呢?spa

  第一:若是先将文件移动到vs以后,vs会以须要开启管理员权限才能够修改来限制咱们对该文件的保存,因此还不如在外面先改了再放进去。线程

  第二:若是不添加这段代码,会报error C2011: “timespec”:“struct”类型重定义的错误,这是由于C++ pthread pthread.h 中的 timespec 和time.h 中的 结构定义重复了 ,同时两个头文件中的条件编译条件不一样,因此形成结构重复定义,简单快速见效的解决方法就是注释pthread.h 头文件中的struct timespce 定义因此要先对pthread进行修改。3d

 

三、Pre-built.2文件夹下有三个文件:

  dll——动态连接库

  include——头文件

  lib——静态连接库

 

 3.1 配置头文件:把include文件夹下的头文件拷贝到vs2017安装目录下

    

 

  3.2 配置静态连接库把lib文件夹下的静态库文件拷贝到vs2017安装目录下

             

 

  3.3配置动态连接库:

               Pre-built.2\dll\x86下的文件拷贝到C:\Windows\SysWOW64目录下

            Pre-built.2\dll\x64下的文件拷贝到C:\Windows\System32目录下

 

四、测试

   

  能够看到编译经过了,那么pthread配置成功了。 

 

 

五、第一个实验,多线程尝试

// pthread_test.cpp: 定义控制台应用程序的入口点。 // #include "stdafx.h" #include<pthread.h> #include<stdio.h> #include<Windows.h> #pragma comment(lib, "pthreadVC2.lib") //total ticket int total_ticket = 100; pthread_mutex_t m_tMutex = PTHREAD_MUTEX_INITIALIZER; //自带函数 //int pthread_create(pthread_t *pThread, const pthread_attr_t *pAttr, void *(*start_routine)(void*), void *arg); //int pthread_join(pthread_t tid, void **value_ptr); //void pthread_exit(void *value_ptr); void function() { printf("this is a thread\n"); } void* thread_start(void* pram) { while (true) { if (total_ticket > 0) { // for(; total_ticket > 0;){ // Sleep(100); //若是把printf合成一句话会出现一直卖零张票的状况。 //加锁时最好把锁起来的范围缩到最小 pthread_mutex_lock(&m_tMutex); printf("%d窗口卖了第", pthread_self()); printf("%d张票\n", total_ticket); // pthread_mutex_lock(&m_tMutex); // printf("%d\n", total_ticket); total_ticket--; pthread_mutex_unlock(&m_tMutex); Sleep(100); } else { pthread_mutex_unlock(&m_tMutex); break; } } return NULL; } int main() { function(); pthread_t tid1; pthread_t tid2; pthread_t tid3; pthread_t tid4; pthread_create(&tid1, NULL, thread_start, NULL); pthread_create(&tid2, NULL, thread_start, NULL); pthread_create(&tid3, NULL, thread_start, NULL); pthread_create(&tid4, NULL, thread_start, NULL); //如下功能相似,实现方法不一样。 // pthread_join(tid1, NULL); // pthread_join(tid2, NULL); // pthread_join(tid3, NULL); // pthread_join(tid4, NULL);  pthread_join(pthread_self(), NULL); getchar(); return 0; }

 

 

  测试结果以下:

  

相关文章
相关标签/搜索