c++ - 英特尔编译器 (C++) 问题与 std::vector 上的 OpenMP 减少有关
问题描述
从 OpenMP 4.0 开始,支持用户定义的缩减。所以我完全从这里定义了 C++ 中 std::vector 的缩减。它适用于 GNU/5.4.0 和 GNU/6.4.0,但它返回随机值以减少 intel/2018.1.163。
这是一个例子:
#include <iostream>
#include <vector>
#include <algorithm>
#include "omp.h"
#pragma omp declare reduction(vec_double_plus : std::vector<double> : \
std::transform(omp_out.begin(), omp_out.end(), omp_in.begin(), omp_out.begin(), std::plus<double>())) \
initializer(omp_priv = omp_orig)
int main() {
omp_set_num_threads(4);
int size = 100;
std::vector<double> w(size,0);
#pragma omp parallel for reduction(vec_double_plus:w)
for (int i = 0; i < 4; ++i)
for (int j = 0; j < w.size(); ++j)
w[j] += 1;
for(auto i:w)
if(i != 4)
std::cout << i << std::endl;
return 0;
}
每个线程将 1 添加到所有 w 条目(其本地 w),最后将所有条目添加到一起(减少)。对于 GNU,所有 w 条目的结果是 4,但使用 intel 编译器是随机的。有谁知道这里发生了什么?
解决方案
这似乎是英特尔编译器中的一个错误,我可以使用不涉及向量的 C 示例可靠地重现它:
#include <stdio.h>
void my_sum_fun(int* outp, int* inp) {
printf("%d @ %p += %d @ %p\n", *outp, outp, *inp, inp);
*outp = *outp + *inp;
}
int my_init(int* orig) {
printf("orig: %d @ %p\n", *orig, orig);
return *orig;
}
#pragma omp declare reduction(my_sum : int : my_sum_fun(&omp_out, &omp_in) initializer(omp_priv = my_init(&omp_orig))
int main()
{
int s = 0;
#pragma omp parallel for reduction(my_sum : s)
for (int i = 0; i < 2; i++)
s+= 1;
printf("sum: %d\n", s);
}
输出:
orig: 0 @ 0x7ffee43ccc80
0 @ 0x7ffee43ccc80 += 1 @ 0x7ffee43cc780
orig: 1 @ 0x7ffee43ccc80
1 @ 0x7ffee43ccc80 += 2 @ 0x2b56d095ca80
sum: 3
在从原始值初始化私有副本之前,它将归约操作应用于原始变量。这会导致错误的结果。
您可以手动添加障碍作为解决方法:
#pragma omp parallel reduction(vec_double_plus : w)
{
#pragma omp for
for (int i = 0; i < 4; ++i)
for (int j = 0; j < w.size(); ++j)
w[j] += 1;
#pragma omp barrier
}
推荐阅读
- python - urlparse 以简单的 url 失败
- php - 如何将引导图像轮播与 WordPress 网站集成
- json - Angular 2,v6:在 assets/*.json 文件上写入并保存 [Typescript]
- javascript - 中继器项目命令未触发但导致页面的所有验证器上的服务器端验证
- java - 花费最多的10名纳税人名单
- python - 将子列表中的浮点数乘以作为字典中的值[编辑]
- ios - AVPlayer 处于 ReadyToPlay 状态但无法开始播放
- c# - 无法使用 PixConverter.ToPix Leptonica C#
- javascript - 使用 webpack 访问 Highcharts.Point 并导入
- php - 显示 PHP 代码而不是解析它的网页