[英]How to parallel a recursive function using OpenMP in C++
這是關於如何使用“任務”指令解決遞歸 function 的問題。 如果您能幫助我解決問題並提出您的想法,我將不勝感激。 問題是:
對於下面的代碼,在 main() 中的某處調用了一個名為 func() 的遞歸 function。 如您所見,遞歸 function 中有 2 個變量(var1 和 var2)控制連續遞歸調用的次數。 通常 var1 的值更大,而 var2 幾乎不會從 boo() 中得到 0 值。 所以,func() 會被連續調用多次,最終停止並返回一個 True/false 值,因此我們需要使用 OpenMp 對其進行並行化以減少其運行時間。
我要應用的是“ #pragma omp task ”指令,因為我知道這是 OpenMp 建議並行化遞歸函數的最佳方式。 但是這個例子似乎與 fibonacci 之類的常規遞歸函數有所不同,遞歸 function fib() 在自身內部被調用了兩次(即 x = fib(n-1) 和 y = fib(n-2) 在 fib(n) 內部),並且我們可以簡單地定義兩個任務並將每個遞歸調用分配給其中一個。 但在下面的示例中,如何定義任務似乎讓我感到困惑。 我可以在調用新的 func() 之前在循環內定義 N 個任務嗎? 如何? 當然,如果有另一種方法(而不是使用“任務”)來有效地並行化這段代碼,那將是非常受歡迎的:
bool func()
{
if(var1 == 0) return True;
else
{
// Do few things, then:
for(int i=0; i<N; i++)
{
// Do few things, then:
boo(); // var2 can changes from 0 to 1 and vise versa here after running boo().
var1--; // var1 has a global positive value at the beginning that is reduced in every iteration of each calling to finally get 0 for stopping recursive calls
if(!var2)
if(func())
return True;
var1++;
// Do few more things
}
// Do few things, then:
return False;
}
}
main()
{
// some initialization
// few things to do, then:
func();
// few thing to show the results
}
並行化形式的代碼類似於下面的一段代碼。 頂部代碼行中注釋了兩個主要問題:
// First problem is how to apply a critical scope at the presence of such an if() statement below.
// Second, how to pull 2 return statements inside the #pragma omp parallel out of the parallel zone.
bool func()
{
if(var1 == 0) return True;
else
{
// Do few things
#pragma omp parallel
{
#pragma omp for
for(int i=0; i<N; i++)
{
// Do few things
#pragma omp critical
{
boo();
var1--;
if(!var2)
} // the critical scope should end here, but does it seem logical/feasible right after if condition?
if(func())
return True;
var1++;
// Do few more things
}
// Do few things, then:
return False;
}
}
}
main()
{
func();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.