#include <iostream>
#include <mutex>
#include <future>
#include <thread>
#include <chrono>
#include <vector>
#include <cstdlib>
using namespace std;
#define COUNT 5000000
long long add(vector <long long >*arr, long long start, long long count)
{
static mutex m;//仅仅初始化一次
int sum(0);//保存结果
for (long long i = 0; i < count; i++)
{
sum += (*arr)[start+i];//根据下标 累加
}
{
lock_guard<mutex>lckg(m);//锁定
cout <<"线程ID:"<< this_thread::get_id() <<" count="<<count<<" sum="<<sum<< endl;
}
return sum;
}
void main()
{
vector<long long>myint(COUNT);//开辟数组大小
for (int i = 0; i < COUNT; i++)//填充数据 赋值
{
myint[i] = (i+1)%1000;//限定数据范围 0~999
//cout << myint[i] << " ";
}
//future < vector<long long>>abc ;
vector<future<long long >>result;
//实现并行计算 获取CPU核心个数 创建线程必须为CPU核心的个数
long long cpus = thread::hardware_concurrency();
cout << "cpu核心个数:" << cpus << endl;
//启动线程 存储结果 使用线程分块
for (long long i = 0; i < cpus * 2; i++)
{
//<span style="font-family: Arial, Helvetica, sans-serif;">//线程切割 </span>线程分块
long long batch_each = COUNT / (cpus * 2);
if (i == cpus * 2-1)
{
batch_each = COUNT - COUNT / (cpus * 2)*i;//让最后一个线程承载多点
}
result.push_back(async(add,&myint,i*batch_each,batch_each));//压入数据
}
//分数据
long long lastresult(0);//最终结果
//汇总数据
for (long long i = 0; i < cpus * 2; i++)
{
lastresult += result[i].get();//累加
}
cout << "lastresult ="<< lastresult << endl;
cin.get();
}
更多资料 · 微信公众号搜索【CTO Plus】关注后,获取更多,我们一起学习交流。
关于公众号的描述访问如下链接