C++11多线程 初步小结
C++ 11引入了thread mitux future几个头文件来处理多线程
#include <iostream>
#include <time.h>
#include <mingw.thread.h> //用的是mingw的编译器 一般可以直接使用#include <thread>
#include <chrono> //精确计时 可以精确到千分之一秒
//download1完成需要5s
void download1()
{
cout<<"begin to download 1"<<endl;
for(int i=0;i<10;i++)
{
mingw_stdthread::this_thread::sleep_for(std::chrono::milliseconds(500));
cout<<"first download percent %"<<(i+1)*10<<endl; //下载进度
}
cout<<"first download completed"<<endl;
}
//download2完成需要8s
void download2()
{
cout<<"begin to download 2"<<endl;
for(int i=0;i<10;i++)
{
mingw_stdthread::this_thread::sleep_for(std::chrono::milliseconds(800));
cout<<"second download percent %"<<(i+1)*10<<endl;
}
cout<<"second download completed"<<endl;
}
void process()
{
cout<<"begin to process 2 download video"<<endl;
}
int main()
{
cout<<"major thread begin"<<endl;
mingw_stdthread::thread d2(download2);
download1(); //主线程来处理download1
//mingw_stdthread::thread d1(download1); //新建立一个线程处理download1
//d1.join();
d2.join(); //如果说不加上d2.join 这时候主线程先下载处理完download1之后 主线程结束了download2还没下载完
process();
system("pause");
return 0;
} 在main函数中 加上d2.join 是这样的: 如果说不加上 因为download1下载更快,需要5s download2需要8s就会导致
这时候主线程先下载处理完download1之后 主线程结束了download2还没下载完运行结果如图:
