gpt4 book ai didi

c - OpenMP 中有默认范围分隔符吗?

转载 作者:行者123 更新时间:2023-11-30 17:20:42 25 4
gpt4 key购买 nike

我是 OpenMP 新手,刚刚完成第一次尝试,这是一个矩阵乘法。我只是想知道 openMP 中是否存在默认的 block 分隔符?以下是我的代码:

#include <stdio.h>
#include <omp.h>
#define MAX_THREADS 4
#define ASIZE 500

int main()
{
/*intialization of 2 matrix*/
long matrixa [ASIZE][ASIZE];
long matrixb [ASIZE][ASIZE];
long matrixc [ASIZE][ASIZE] = {0};
for(int i=0; i<ASIZE; i++)
for(int j=0;j<ASIZE; j++)
{
matrixa [i][j] = 1;
matrixb [i][j] = j;
}

omp_set_num_threads(MAX_THREADS);

#pragma omp parallel
{
long cprivate [ASIZE][ASIZE] = {0};
#pragma omp for
for(int i =0 ;i<ASIZE; i++)
for(int j=0; j<ASIZE; j++)
for(int k=0; k<ASIZE; k++)
cprivate[i][j]+=matrixa[i][k]*matrixb[k][j];

#pragma omp critical
for(int i =0 ;i<ASIZE; i++)
for(int j=0; j<ASIZE; j++)
matrixc[i][j]+=cprivate[i][j];

//#pragma omp barrier
if(omp_get_thread_num() ==0)
for(int i=0; i<50; i++)
printf("Snap of C array %lu \n", matrixc[1][i]); //print out chunk of the first row!

}
}

我这样想是因为无论我是否添加#pragma omp Barrier,我都能得到预期的结果,这应该是#pragma omp完整执行后的结果关键 block 。

问题

@为什么有或没有#pragma omp Barrier没有什么区别有什么想法吗?

@我还注意到,一旦我将数组大小增加到600百,执行.o文件时就会警告段错误,我最初猜测它来自int范围(我已将数组类型从int[]修改为long[]),没有区别。

最佳答案

您的代码可能会失败,因为您正在使用自动存储。您应该使用动态或静态存储。这是使用静态存储对代码进行的修复

#include <stdio.h>
#include <stdlib.h>
#define ASIZE 1000

long matrixa [ASIZE][ASIZE];
long matrixb [ASIZE][ASIZE];
long matrixc [ASIZE][ASIZE]; //set to zero by default with static storage

int main() {
for(int i=0; i<ASIZE; i++) {
for(int j=0;j<ASIZE; j++) {
matrixa [i][j] = 1;
matrixb [i][j] = j;
}
}

#pragma omp parallel for
for(int i=0 ;i<ASIZE; i++) {
for(int j=0; j<ASIZE; j++) {
long sum = 0;
for(int k=0; k<ASIZE; k++) {
sum += matrixa[i][k]*matrixb[k][j];
}
matrixc[i][j] = sum;
}
}
for(int i=0; i<50; i++) printf("Snap of C array %lu \n", matrixc[1][i]);
}

如果您想为每个线程静态分配缓冲区,那么您需要使用threadprivate,否则使用动态分配。

您不需要使用屏障的原因是屏障对于关键和许多其他构造来说是隐式的。要消除隐式障碍,在某些情况下可以使用 nowait(例如 #pragma omp parallel for nowait)。

关于c - OpenMP 中有默认范围分隔符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28466410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com