2014-12-02 24 views
4

我有以下代碼:減少變量是外上下文私人

void simulation (MD *md){ 

    double sum; 
    #pragma omp parallel private (move) 
    { 

     for(move = 0; move < maxIterations; ++move) 
     { 
       cicleDoMove(md); 
       cicleForces(md); 
       cicleMkekin(md,sum); 
       // ... 
     } 
    } 
} 

其中:

void cicleMkekin(Md *md, double sum){ 

    #pragma omp for reduction(+ : sum) 
    for (i = 0; i < md->mdsize; i++) 
    { 
     sum += mkekin(..); 
    } 
    // .. 
} 

我得到了以下錯誤:

"reduction variable 'sum' is private in outer context" 

把變量SUM共享不是私人的,實際上如果我將模擬代碼更改爲:

void simulation (MD *md){ 

     double sum; 
     #pragma omp parallel private (move) 
     { 

      for(move = 0; move < maxIterations; ++move) 
      { 
        cicleDoMove(md); 
        cicleForces(md); 

        #pragma omp for reduction(+ : sum) 
        for (i = 0; i < md->mdsize; i++) 
        { 
         sum += mkekin(..); 
        } 
        // ... 
      } 
     } 
    } 

它完美地工作。

是否有反正我可以使用我的第一個代碼版本沒有得到那個錯誤?或者我做錯了什麼?

+2

您正將'sum'按值傳遞給'cicleMkekin' - 在這種情況下,它不可能是一個共享變量,因爲'cicleMkekin'在每個線程中都接收到一個單獨的值 - 副本。 – 2014-12-04 07:44:09

+0

是的,我第一次嘗試通過引用傳遞,但我不能用它在還原函數。我知道這個錯誤是有道理的,我只是在尋找一些不會使用錯誤共享的解決方法。無論如何,我最終都會使用所有線程共享的數組。我將刪除「在我看來,OpenMp認爲論點是私人的或某些東西」這是沒有意義的。 – dreamcrash 2014-12-04 22:08:36

回答

7

在這種特殊情況下OpenMP可能會有點混亂。該specification規定(§2.14.3.6)認爲:

A list item that appears in a reduction clause of a worksharing construct must be shared in the parallel regions to which any of the worksharing regions arising from the worksharing construct bind.

而且它說(§2.14.1.1),C和C++中,

Variables with automatic storage duration that are declared in a scope inside the construct are private.

在你的情況下,變量sum聲明在函數cicleMkekin的調用範圍內,並且作爲函數參數具有自動存儲持續時間。因此,當您在並行區域內(或者從與您的程序的執行相符的隱式頂層並行區域)調用cicleMkekin時,sum被認爲是一個私有變量。因此,您的裁減條款確實是非法的,您收到的錯誤信息實際上可能會引起混淆。

在您已將代碼手動內聯到cicleMkekin的代碼版本中,您聲明變量sum在並行區域之外。如果沒有default子句或者該變量的所謂明確確定的數據共享屬性,則這樣的變量實際上是共享的(§2.14.1),因此該代碼版本中的reduction子句是合法的。

+0

是的,這似乎是這樣,我最終做了一個解決辦法,同時試圖避免錯誤的分享,謝謝你的回答,我會等待更多的答案1天,如果沒有人反駁你的答案,那麼我會接受它。 – dreamcrash 2014-12-02 20:57:37

+0

這是否表示以下https://stackoverflow.com/a/41062993/195787不起作用? – Royi 2017-10-11 02:17:54