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

 

 

  測試結果如下:

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM