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

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

     

  我们选第二个zip,第一个是给linux系统的啦,不过老师好像说linux系统本身就支持多线程(应该是在linux里可以通过指令直接下载,正常情况下不需要再载安装包放入虚拟机里)。

  打开后找到Pre-built.2>include,可以看见三个头文件,这是三个我们需要去移动到vs里的头文件,先留着。

 

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

     这是原本文件的代码:

     

 

     我们需要在35行的位置添加下面一条代码:

         #define HAVE_STRUCT_TINMESPEC

 

           

 

  为什么要在将文件移动到vs文件夹内之前修改呢?

  第一:如果先将文件移动到vs之后,vs会以需要开启管理员权限才可以修改来限制我们对该文件的保存,所以还不如在外面先改了再放进去。

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

 

3、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目录下

 

4、测试

   

  可以看到编译通过了,那么pthread配置成功了。 

 

 

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

// 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;
}

 

 

  测试结果如下:

  

 

posted @ 2019-03-16 21:23  喵喵喵喵?  阅读(3060)  评论(1编辑  收藏  举报