1> 首先下載TDM-GCC-64。 網址爲:http://sourceforge.net/projects/tdm-gcc/?source=typ_redirectios
2>打開c-free--構建--構建選項--點擊構建配置的右上角,如圖。c++
3>點擊新建配置--MinGW--名稱本身起。 如圖。多線程
4>點擊編譯--把下方原始參數改成: -std=c++11 -DDEBUG 如圖。併發
5>點擊路徑--點擊刪除所有路徑--自動檢測--找到TDM-GCC-64的路徑--雙擊找到的路徑--肯定。如圖。函數
至此,應該就能用了,留一個多線程的例子,進行測試。測試
ThreadEx.hthis
#ifndef ThreadEx__h #define ThreadEx__h #include <string> using namespace std; class ThreadEx { public: //構造函數 ThreadEx(); //線程任務方法 void taskForThread(string preFix,string afterFix); }; #endif
#include "ThreadEx.h" #include <thread> #include <iostream> #include <chrono> using namespace std; ThreadEx::ThreadEx() { thread t1(&ThreadEx::taskForThread,this,"[","]"); thread t2(&ThreadEx::taskForThread,this,"<",">"); //要點: //一、主線程不能先於子線程任務完成,不然子線程任務走不完就拉倒了。 //二、主線程中啓動子線程後(採用局部對象法),要麼join,要麼detach。 // 這是由於線程對象在被析構(~thread())以前必須調用一次join或detach, // 不然運行報錯的。 //官方英文解釋以下: //The trouble you are encountering is a result of the stopThread going out of scope on the stack. //The C++ standard has the following to say about this: //30.3.1.3 thread destructor [thread.thread.destr] //~thread(); //If joinable() then terminate(), otherwise no effects. //[ Note: Either implicitly detaching or joining ajoinable() thread in its destructor could result in difficult to debug correctness (for detach) //or performance (for join) bugs encountered only when an exception is raised. Thus the programmer must ensure that the destructor is never executed //while the thread is still joinable. — end note ] //What this means is that you should not let threads go out of scope without first calling either join() ordetatch(). //----------------------------------------------------------- //這裏的休息模擬主線程幹活 //std::this_thread::sleep_for(std::chrono::milliseconds(5000)); //主線程啓動子線程後調用join方法,確保 //子線程和主線程合併,不然運行報錯 //可是這樣主線程和子線程之間實際就不是併發了 //主線程會一直等待,直至子線程運行結束 //另外當調用join函數時,調用線程阻塞等待目標線程終止,而後回收目標線程的資源。 //t1.join(); //t2.join(); //----------------------------------------------------------- //----------------------------------------------------------- //detach方法功能爲將子線程分離,交由操做系統處理。 //當子線程主函數執行完以後,線程就結束了,運行時庫負責清理與該線程相關的資源。 t1.detach(); t2.detach(); //這裏的休息模擬主線程幹活 std::this_thread::sleep_for(std::chrono::milliseconds(5000)); //----------------------------------------------------------- cout<<endl<<"main end"<<endl; } void ThreadEx::taskForThread(string preFix,string afterFix) { for(int i=0;i<100;i++) { cout<<preFix<<i<<afterFix; //休眠20毫秒 std::this_thread::sleep_for(std::chrono::milliseconds(20)); } }
main.cppspa
#include <iostream> #include <thread> #include <chrono> #include "ThreadEx.h" using namespace std; int main(int argc, char *argv[]) { new ThreadEx(); return 0; }
版權聲明:本文爲博主原創文章,未經博主容許不得轉載。操作系統