在windows平台下,使用vs2017新建了一个控制台项目,实践C++11新特性thread。实践的主要思想是通过建立一个vector存入大量数据,将数据分成两半,一半主线程操作,一半子线程操作,对比单线程运行时间,是否提升了效率。
#include<iostream>
#include<thread>//线程头文件
#include<future>//简单说std::future提供了一种访问异步操作结果的机制
#include<cmath>//数学操作头文件
#include<vector>
#include<chrono>//获取本机器参考线程数的头文件
#include<cstdlib>//C语言中的stdlib.h在C++被重命名为cstdlib
#include<ctime>////C语言中的time.h在C++被重命名为ctime
using namespace std;
//沉重的计算事实上就算这样计算也很快
double caculate(double v)
{
if (v<=0)
{
return v;
}
this_thread::sleep_for(chrono::milliseconds(10));//线程延时操作,为了模拟数据很多处理慢
return sqrt((v*v + sqrt(v - 5)*(v + 2.5) / 2.0) / v);
}
//for_each
template<typename Iter,typename Fun>
double visitRange( thread::id id,Iter iterBegin, Iter iterEnd, Fun func)
{
auto curId = this_thread::get_id();//获取主线程ID
if (id == curId)
{
cout << curId << "hello main thread\n" << endl;
}
else
{
cout << curId << "hello work thread\n";
}
double v = 0;
for (auto iter = iterBegin; iter < iterEnd; ++iter)
{
v += func(*iter);
}
return v;
}
//多线程 处理一组数据 将一组数据分为两半
int main()
{
auto mainThreadId = this_thread::get_id();
vector<double> v;
for (int i = 0; i < 1000; ++i)
{
v.push_back(rand());
}
cout << v.size() << endl;
double value = 0.0;
auto nowc = clock();//记录时间
//单线程总数据操作
for (auto& info :v)
{
value += caculate(info);
}
auto finc = clock();//记录时间
cout << "time value =" << finc- nowc << endl;
cout << "value =" <<value << endl;
auto midIter = v.begin() + (v.size() / 2);//分割vector
//第二部分
nowc = clock();//记录子线程时间
double anotherv = 0.0;
auto iterEnd = v.end();
//传入线程
thread s([&anotherv, mainThreadId, midIter, iterEnd]()
{
anotherv = visitRange(mainThreadId,midIter, iterEnd, caculate);
});
auto id = s.get_id(); //获取s线程id
auto halfv = visitRange(mainThreadId,v.begin(), midIter, caculate);
s.join();
finc = clock();//记录子线程时间
cout << "duo timevalue =" << finc - nowc << endl;
cout << "anotherv =" << (anotherv) << endl;
cout << "halfv =" << (halfv) << endl;
cout << "Allvalue =" << (halfv + anotherv) << endl;
}