C++基础-并行计算求和(async)
2021/6/29 9:20:51
本文主要是介绍C++基础-并行计算求和(async),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
并行计算使用的是async, 通过每一个线程都进行相同的计算,最后在vector<future<int>>result; 将结果进行相加
全部代码
// // 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(); }
这篇关于C++基础-并行计算求和(async)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-29易优CMS安装常见问题汇总-icode9专业技术文章分享
- 2024-06-28易优新手必读安装教程-icode9专业技术文章分享
- 2024-06-28忘记eyoucms后台密码怎么办?-icode9专业技术文章分享
- 2024-06-26终极指南:Scrum中如何设置需求优先级
- 2024-06-26AI大模型企业应用实战(25)-为Langchain Agent添加记忆功能
- 2024-06-26小白家庭 nas 搭建方案-icode9专业技术文章分享
- 2024-06-23AI大模型企业应用实战(14)-langchain的Embedding
- 2024-06-23AI大模型企业应用实战(15)-langchain核心组件
- 2024-06-23AI大模型企业应用实战(16)-langchain核心组件
- 2024-06-23AI 大模型企业应用实战(06)-初识LangChain