如何广播OpenMP单块的结果

How to broadcast result from OpenMP single block

本文关键字:OpenMP 单块 结果 广播 何广播      更新时间:2023-10-16

我被一个看起来微不足道的问题困住了(也许现在还为时过早)。从在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);
   /* ... */
}

一个相当不优雅的解决方案是用reduction:

single块转换为parallel for块。
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)子句,它确实做到了这一点—它将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;
}