多线程并行数组求和(交错配对模式)
来源:互联网 发布:中金数据系统 编辑:程序博客网 时间:2024/05/22 15:53
利用OpenMP的多线程,对数组进行分组求和,最后对每个线程的局部求和结果进行求和。
这里采用交错配对(下文还有相邻配对),如图所示。
#include"iostream"#include"omp.h"using namespace std;#define NUM_THREADS 4//并行规约template <class T>T omp_reduction(T*data ,int length){if (length == 1) return *data;int strize = length / 2;for (int i = 0; i < strize; i++){data[i]+=data[i+strize];}omp_reduction(data,strize);}//数组初始化template<class T>void datainit(T* data,int length){for (int i = 0; i < length; i++){data[i]=i;}}//计算结果检查template<class T>bool check_result(T data1,T data2,int length){if (data1!=data2) return false;return true;}int main(){//基本参数设置const int datalen=256;int* data=new int[datalen];int local_sum[NUM_THREADS];int total_sum_serial=0;int total_sum_omp=0;int step=datalen/NUM_THREADS;bool check_ok;//数组初始化datainit(data,datalen);//设置并启动4个并行的omp线程omp_set_num_threads(NUM_THREADS);#pragma omp parallel {int index=omp_get_thread_num();//获取当前线程号local_sum[index]=omp_reduction(data+index*step,step);//调用规约函数计算当前线程所分配的任务}//对线程的局部求和结果进行求和for (int i = 0; i < NUM_THREADS; i++){total_sum_omp+=local_sum[i];}
//串行数组求和datainit(data,datalen);for (int i = 0; i < datalen; i++){total_sum_serial+=data[i];}check_ok=check_result(total_sum_omp,total_sum_serial,datalen);if (check_ok){cout<<"omp并行规约计算正确!"<<endl;}else{cout<<"omp并行规约计算错误!"<<endl;}cin.get();return 0;}
阅读全文
0 0
- 多线程并行数组求和(交错配对模式)
- 多线程并行数组求和(相邻配对模式)
- CUDA并行规约(交错配对)
- CUDA并行规约(交错配对-展开规约)
- CUDA并行规约(交错配对-展开线程)
- CUDA并行规约(交错配对-完全展开-终极版)
- 交错数组
- 交错数组
- 交错数组
- 数组配对(算法)
- 交错数组(C# 编程指南)
- 交错数组 (齿轮数组、数组中的数组)
- 多维数组,交错数组
- java 多线程并行求和 之 join() 方法应用
- 并行(多线程)
- Code51交错数组示例
- C#交错数组浅析
- C#交错数组
- linux————jdk安装
- 服务器搭建(基础简化版)
- 浅谈ajax和easyUI
- html的<embed>标签
- Spring手动扫描包路径及容器外获取Bean实例
- 多线程并行数组求和(交错配对模式)
- 随机器学习兴起的Julia编程语言
- RabbitMQ使用记录
- vs2013下如何调试带输入参数的程序
- [leetcode] 740. Delete and Earn
- scala + sbt + intellij
- 锁存器(74HCT573)使用
- 搭建Apache虚拟目录
- 限制字数, 并且实时显示字数的EditText