一、首先要配置環境,載包。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; }
測試結果以下: