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; }
版权声明:本文为博主原创文章,未经博主容许不得转载。操作系统