【发布时间】:2017-11-20 03:24:01
【问题描述】:
我有一个随机数数组,我需要将它分成 4 个线程,然后使用并行性找到数组中的最大数。我是使用线程的新手,我对编译指示函数知之甚少。但是,我尝试使用下一个代码。
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <omp.h>
#define N 10000
int searchMax(int *a, int n){
int max, i;
max = a[0];
#pragma omp parallel for
for (i = 0; i < n; i++){
#pragma omp critical
{
if (a[i] > max)
max = a[i];
}
}
return(max);
}
int main(){
int i, arr[N], max;
time_t t;
clock_t tini, tfin;
double tdur;
srand((unsigned) time(&t));
for (i = 0; i < N; i++)
arr[i] = rand();
tini = clock();
max = arr[0];
for (i = 1; i < N; i++)
if (arr[i] > max)
max = arr[i];
tini = clock();
max = searchMax(arr, N);
tfin = clock();
tdur = (double)(tfin - tini) / CLOCKS_PER_SEC;
printf("max number: %d time: %lf\n", max, tdur);
return(0);
}
问题是这段代码只划分了for循环。我不知道如何将数组分成线程并让它们每个都执行for循环。
【问题讨论】:
-
看到临界区生成了所有将被放入线程的循环代码,您从并行性中获得的收益很少。我建议采取分而治之的方法,但即便如此,收益也将微乎其微。
-
在共享内存并行计算中,例如 OpenMP 用于,您不要在线程之间划分数组 - 每个线程对它具有相同的访问权限。当您编写代码时,每个线程都会获得其自己的
i值子集以供使用,从而获得一组a元素。现在参考您的教程和参考资料,了解如何使用 OpenMP 进行 reductions(特别是在 max 运算符上),并了解 shared和私有变量。
标签: c arrays multithreading openmp pragma