gpt4 book ai didi

c++ - 如何从 OpenMP 单 block 广播结果

转载 作者:行者123 更新时间:2023-11-28 03:21:32 26 4
gpt4 key购买 nike

我遇到了一个看似微不足道的问题(也许现在还为时过早)。从在 omp parallel 区域内调用的函数中,我想返回一个值,其中 (1) 在每个线程上都必须相同,但 (2) 在 omp single 中计算> 阻止。我怎样才能做到这一点?这是一个小代码片段:

// must work correctly when called from within omp parallel region
// this version is flawed. please suggest corrections
int func(vector<int>&args)
{
int x;
#pragma omp single
x = foo(args); // foo() must be called in single block
// would need to broadcast x to all threads here
return x; // error: x only set for thread which executed foo()
}

// possible usage (elsewhere, you're not allowed to change this code)
#pragma omp parallel
{
/* ... */
int y = func(args);
/* ... */
}

一个相当不优雅的解决方案是将 single block 转换为 parallel for with reduction:

int func(types args)
{
int x=0;
#pragma omp for reduction(+:x)
for(int i=0; i<1; ++i)
x = foo(args);
return x;
}

但肯定有更好的解决方案。

最佳答案

解决方案非常简单 - 只需附加 copyprivate(x) 子句,它就是这样做的 - 它广播所列私有(private)变量实例的值single 构造到其他线程:

int func(vector<int>&args)
{
int x;
#pragma omp single copyprivate(x)
x = foo(args); // foo() must be called in single block
// would need to broadcast x to all threads here
return x;
}

关于c++ - 如何从 OpenMP 单 block 广播结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15291097/

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