并行计算使用的是async, 通过每一个线程都进行相同的计算,最后在vector
全部代码
//
// Created by Administrator on 2021/6/29.
//
#include<iostream>
#include<thread>
#include<future>
#include<vector>
#include<cstdlib>
using namespace std;
#define COUNT 1000000
int add(vector<int>*arr, int start, int count)
{
static mutex m; //只会初始化一次
int sum(0); //保存结果的作用
for(int i = 0; i < count; i++){
sum += (*arr)[start + i];
}
{
//显示结果必须, 仅仅计算多余, 加锁
lock_guard<mutex> lck(m); //锁定
cout << "thread" << this_thread::get_id << ",count" <<
",sum=" << sum << endl; //打印结果
}
return sum;
}
int main()
{
vector<int>data(COUNT); //数组, 100万
for(int i = 0; i < COUNT; i++)
{
data[i] = (i + 1) % 1000; //0-999
}
vector<future<int>>result; //结果数组
int cpus = thread::hardware_concurrency(); //CPU核心的个数
for(int i = 0; i < cpus * 2; i++)
{
int batch_each = COUNT / (cpus * 2); //
if(i == (cpus * 2) - 1) {
batch_each = COUNT - COUNT / (cpus * 2) * i; //最后一个承担更多的计算
}
//不断压入结果
result.push_back(async(add, &data, i * batch_each, batch_each)); //返回结果
}
int lastresult(0);
for(int i = 0; i < cpus * 2; i++)
{
lastresult += result[i].get(); //汇总结果
}
cout << "lastresult=" << lastresult << endl;
cin.get();
}
//
// Created by Administrator on 2021/6/29.
//
#include<iostream>
#include<thread>
#include<future>
#include<vector>
#include<cstdlib>
using namespace std;
#define COUNT 1000000
int add(vector<int>*arr, int start, int count)
{
static mutex m; //只会初始化一次
int sum(0); //保存结果的作用
for(int i = 0; i < count; i++){
sum += (*arr)[start + i];
}
{
//显示结果必须, 仅仅计算多余, 加锁
lock_guard<mutex> lck(m); //锁定
cout << "thread" << this_thread::get_id << ",count" <<
",sum=" << sum << endl; //打印结果
}
return sum;
}
int main()
{
vector<int>data(COUNT); //数组, 100万
for(int i = 0; i < COUNT; i++)
{
data[i] = (i + 1) % 1000; //0-999
}
vector<future<int>>result; //结果数组
int cpus = thread::hardware_concurrency(); //CPU核心的个数
for(int i = 0; i < cpus * 2; i++)
{
int batch_each = COUNT / (cpus * 2); //
if(i == (cpus * 2) - 1) {
batch_each = COUNT - COUNT / (cpus * 2) * i; //最后一个承担更多的计算
}
//不断压入结果
result.push_back(async(add, &data, i * batch_each, batch_each)); //返回结果
}
int lastresult(0);
for(int i = 0; i < cpus * 2; i++)
{
lastresult += result[i].get(); //汇总结果
}
cout << "lastresult=" << lastresult << endl;
cin.get();
}
原文链接: https://www.cnblogs.com/my-love-is-python/p/14948191.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/211776
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!