簡體   English   中英

使用 MPI 為每個等級創建數組

[英]Creating array for each rank using MPI

我正在練習這段代碼,但我的問題是我無法確保為各個等級創建的每個 x 實際上都與正確的等級相關。

#include <iostream>
#include "mpi.h"
using namespace std;
const int N = 3;
void print(int x[N]) {
    for (int i = 0; i <N ;i++) {
        cout << x[i] << "\t";
    }
}

int main()
{
    MPI_Init(NULL, NULL);
    int rank;
    int size;
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    cout << " My rank is : "<<rank << endl; 

    int x[N];
    for (int i = 0; i < N;i++) {
        x[i] = 2*rank + i;
    }
    print(x);
    MPI_Finalize();
}

結果是:

 My rank is : 0
 My rank is : 2
 My rank is : 1
 My rank is : 3
6       7       8
0       1       2
2       3       4
4       5       6

查看結果,很明顯已經為排名正確創建了 x,但我期待這個結果。 我不知道為什么我沒有得到這個。

   My rank is : 0
   0       1       2
   My rank is : 2
   4       5       6
   My rank is : 1
   2       3       4
   My rank is : 3
   6       7       8

cout緩沖區 output 直到遇到換行符或 output 的結尾(在程序退出時)。

在您的情況下,這里只有一個換行符:

   cout << " My rank is : "<<rank << endl; 

因此,當程序結束時,output 的 rest 被寫入控制台,這發生在MPI_Finalize()的一部分同步等級之后。 因此,它充當屏障,同步 output。

嘗試添加cout << endl; print()結束時:

void print(int x[N]) {
    for (int i = 0; i <N ;i++) {
        cout << x[i] << "\t";
    }
    cout << endl; // <------ here
}

然后你應該看到你預期的交錯 output。

 My rank is : 0
0       1       2
 My rank is : 1
2       3       4
 My rank is : 2
4       5       6
 My rank is : 3
6       7       8

甚至

 My rank is : 3
6       7       8
 My rank is :  My rank is : 10
0       1       2

2       3       4
 My rank is : 2
4       5       6

- 不同等級的 output 並沒有真正同步。

使用MPI_Gather並在 root 中打印數據可以解決問題!

暫無
暫無

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

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