0
我被困在一個看起來微不足道的問題(可能現在太早了)。從omp parallel
區域內調用的函數中,我想返回一個值(1)必須在每個線程上相同,但(2)在omp single
塊中計算。我怎樣才能做到這一點?這裏是一個小的代碼片段:如何從OpenMP單塊廣播結果
// 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
塊鑄造成一個parallel for
與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;
}
但可以肯定,必須有一個更好的解決方案。