【发布时间】:2015-09-09 14:54:41
【问题描述】:
我写了一个程序如下:
#include "omp.h"
#include "stdio.h"
int main()
{
int i, j, cnt[] = {0,0,0,0};
#pragma omp parallel
{
int cnt_private[] = {0,0,0,0};
#pragma omp for private(j)
for(int i = 1 ; i <= 10 ; i++) {
for(j = 1 ; j <= 10 ; j++) {
int l= omp_get_thread_num();
cnt_private[l]++;
}
#pragma omp critical
{
for(int m=0; m<3; m++){
cnt[m] = cnt_private[m];
}
}
printf("%d %d %d %d %d\n",i,cnt[0],cnt[1],cnt[2],cnt[3]);
}
}
return 0;
}
它应该打印每个线程对每个 i 执行的次数。由于只有一个线程采用特定的 i,因此预期输出应满足每行之和为 100。但我得到的输出形式为:
1 10 0 0 0
2 20 0 0 0
3 30 0 0 0
7 0 0 10 0
8 0 0 20 0
9 0 0 0 0
10 0 0 0 0
4 0 10 0 0
5 0 20 0 0
6 0 30 0 0
问题出在哪里?会不会是我对 OpenMP 的基本理解?还是我的还原过程错误? (我使用 GNU gcc 编译器和 4 核机器) 编译步骤:
g++ -fopenmp BlaBla.cpp
export OMP_NUM_THREADS=4
./a.out
【问题讨论】:
-
你声明了 i 两次。不是错误,而是...
-
每个线程都有自己的私有cnt_private,所以它只会有来自自己线程ID的条目;而cnt 中只有一份cnt_private 数据的副本——从哪个线程运行当前的
i索引。所以你所拥有的(过早地停止m循环)是正确的。特别是,您没有对cnt进行缩减。
标签: c++ parallel-processing openmp computation