簡體   English   中英

無法通過MPI_send發送整個矢量

[英]Cant send the whole vector through MPI_send

我一直在努力學習MPI。 當我嘗試運行以下代碼時,我得到錯誤的輸出。

if (world_rank == 0){

    vector<vector<double> > n(4,vector<double>(4));

    srand(time(NULL));

    for(int i=0; i<4 ;i++){
        for(int j=0;j<4;j++){
            n[i][j] = (double)rand()/RAND_MAX;
            cout << n[i][j] << " ";
        }
        cout << endl;
    }
    MPI_Send((void*)&n[0][0],16*sizeof(double),MPI_BYTE,1,0,MPI_COMM_WORLD);
}else{
    MPI_Status status;

    vector<vector<double> > n(4,vector<double>(4));

    MPI_Probe(0,0,MPI_COMM_WORLD,&status);

    int size;

    MPI_Get_count(&status,MPI_BYTE,&size);

    cout << endl << size << endl;

    MPI_Recv((void*)&n[0][0],16*sizeof(n[0][0]),MPI_BYTE,0,0,MPI_COMM_WORLD,MPI_STATUS_IGNORE);

    cout.flush();
    cout << endl;

    for(int i=0; i<4 ;i++){
        for(int j=0;j<4;j++){
            cout << n[i][j] << " ";
        }
        cout << endl;
    }
}

我得到除了最后3個之外的所有雙重值。像這樣。

0.824468 0.752417 0.757125 0.470763 
0.251683 0.703306 0.157991 0.764423 
0.815327 0.0402807 0.897109 0.313816 
0.997203 0.796665 0.0522305 0.797733 

128

0.824468 0.752417 0.757125 0.470763 
0.251683 0.703306 0.157991 0.764423 
0.815327 0.0402807 0.897109 0.313816 
0.997203 0 0 0

任何人都可以告訴我為什么會這樣嗎? 我運行相同的代碼大約一百次仍然得到相同的輸出(當然具有不同的值)但最后三個總是0。

但當我將大小從16改為19時,我得到了所有的值。

我還有另一個疑問。 有時輸出(來自節點0和1的值)重疊。 任何人都可以告訴我如何制止或至少解釋為什么會發生這種情況。 我的意思是即使send和recv是阻塞功能。 如何在節點0之前打印節點1的輸出

您將2D數據n定義為vector<vector<double> > ,使其在內存中不連續。 因此,你不能簡單地使用MPI傳輸它(有很多方法可以實現它,但你最好只是讓內存連續)。

為了使你的記憶連續,你可以聲明你的n (未經測試):

vector<double> ndata(4*4); //contiguous storage of the actual data
vector<double*> n(4);      //vector of pointers to access the actual data
for (int i=1; i<4; i++)    //initialisation of the pointers to the data
    n[i] = &ndata[4*i];

當然,有更好的方法可以在C ++中為多維數組定義連續存儲,但這只是對您的直接問題的快速解決方案。 例如,請參閱此答案以獲得更好的結構。

而BTW,你的MPI_Send()MPI_Recv()調用應該使用4*4 MPI_DOUBLE而不是4*4*sizeof(double) MPI_BYTE

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM