利用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;
}