2013-03-08 44 views
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 forreduction

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

但可以肯定,必須有一個更好的解決方案。

回答

2

解決的辦法很簡單 - 只是追加了copyprivate(x)條款,這正是這麼做的 - 它廣播在single構建用於其他線程所列出的私有變量的實例(或多個)的值(S):

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; 
}