2012-02-22 83 views
13

嗨,只是想知道這是正確的方式去有一個正常的循環,但有兩個減少,這是正確的做法下面?這是否會有更多的兩個減少工作。有一個更好的方法嗎? 也有沒有機會將其與MPI_ALLREDUCE命令集成?openmp並行for循環與兩個或更多的減少

heres the psuedo code 

     #pragma omp parallel for \ 
     default(shared) private(i) \ 
     //todo first reduction(+:sum) 
     //todo second reduction(+:result) 

     for loop i < n; i ++; { 
     y = fun(x,z,i) 
     sum += fun2(y,x) 
     result += fun3(y,z) 
     } 

回答

19

可以通過指定多個變量之間用逗號分隔,即列表做減少:

#pragma omp parallel for default(shared) reduction(+:sum,result) ...

專用線程變量將爲sum創建並result將使用相結合+,並分配給線程塊末尾的原始全局變量。

此外,變量y應標記爲私人。

https://computing.llnl.gov/tutorials/openMP/#REDUCTION

+0

非常感謝你 – pyCthon 2012-02-22 03:27:43

+1

如果有什麼要例如不同的操作'+'和'max'? – worenga 2016-01-11 13:16:42

+1

@mightyuhu查看我的回答 – Azmisov 2016-05-17 19:49:45

3

你可以簡單地添加其他reduction條款:

#include <iostream> 
#include <cmath> 

int main(){ 
    double sum_i = 0, max_i = -1; 
    #pragma omp parallel for reduction(+:sum_i), reduction(max:max_i) 
    for (int i=0; i<5000; i++){ 
     sum_i += i; 
     if (i > max_i) 
      max_i = i; 
    } 
    std::cout << "Sum = " << sum_i << std::endl; 
    std::cout << "Max = " << max_i << std::endl; 
    return 0; 
} 
+0

它不適用於GCC 7.1。任何想法如何應用2個不同的減少? – Royi 2017-10-11 02:30:09