2012-03-10 20 views
3

我對MPI(使用C)比較陌生,並且在使用MPI_Bcast向所有進程發送int時遇到了一些麻煩。MPI_Bcast難點:如何確保「正確的」根目錄正在廣播

在我的代碼中,我決定哪個等級是for循環中的根,其中不同的進程負責不同的循環元素。然後,我想Bcast從根到所有進程的結果,除非所有非根進程都不知道誰會期待bcast,所以不會收到它。

代碼塊看起來是這樣的:

for (iX=start; iX<end; iX++) 
//start and end are the starting row and ending row for each processes, defined earlier 

    for (int iY=1; iY<nn; iY++) 

    // do some calculations 

    if (some condition) 

     int bcastroot = rank; // initialized above 
     int X = 111; // initialized above 

    else 
     //do other calculations 

    end 
end 

MPI_Bcast(&X, 1, MPI_INT, bcastroot, comm); 

// remainder of code and MPI_FINALIZE 

當我執行這個代碼,無論bcastroot默認(值於所有非根進程)和根競爭,所以X是不正確廣播。我不知道X的價值,也不能事先預測根,所以我不能提前定義它。

我嘗試初始化bcastroot = -1,然後將其設置爲等級,但這不起作用。有沒有一種方法可以在不爲所有進程設置根的情況下對此值進行Bcast?

感謝, JonZor

+0

如果您不知道根目錄,則需要進行通信。也許bcast在這裏不是正確的選擇?如果能解決你的問題,你有沒有看過MPI_Allreduce? – haraldkl 2012-03-10 21:21:11

回答

5

有沒有辦法做一個MPI_Bcast,其中接收器不知道的根源是什麼。如果你知道只會有一個根,你可以先做一個MPI_Allreduce在其上達成一致:

int root, maybe_root; 
int i_am_root = ...; 
maybe_root = (i_am_root ? rank : 0); 
MPI_Allreduce(&maybe_root, &root, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD); 

那麼每個等級都知道同根,你可以做你的廣播。

+0

謝謝,耶利米,非常感謝。這很好!在我閱讀您的回覆之前,我實際上剛剛開始提出相同的解決方案。 – user1261516 2012-03-10 22:12:32