使用 MPI 使用 2 个不同的进程更新数组

Updating an array using 2 different process using MPI

我正在尝试使用 2 个进程更新数组 int arr[2],其中第一个索引将由进程 1 填充,第二个索引将由进程 2 填充。我为一样

#include<stdio.h>
#include"mpi.h"

int main( int argc, char *argv[])
{
    int arr[2];
      
    
    MPI_Init(&argc, &argv);
    
    int myrank, size; //size will take care of number of processes 
    
    
    
    MPI_Comm_rank(MPI_COMM_WORLD, &myrank) ;
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    
    if(myrank==0)
    arr[0]=1;
    
    if(myrank==1)
    arr[1]=2;
    
     MPI_Finalize();
    
    printf("%d %d\n",arr[0],arr[1]);
    
    
    return 0;
        
        
}

正如预期的那样,输出是

0 2
1 0

或者有时(当进程 1 先到达打印语句时)

1 0
0 2

我的问题是,我在 MPI_Init 之外声明了数组,并且在 MPI_Finalize() 之后打印数组,那么为什么两个进程都在打印?有没有办法存储输出

1 2

在数组中,实际上没有将数据从一个进程发送到另一个进程?

My question is, I have declared the array outside MPI_Init and I am printing the array after MPI_Finalize(), then why both the processes are printing?

来自MPT_INIT 可以阅读:

The MPI standard does not say what a program can do before an MPI_INIT or after an MPI_FINALIZE. In the MPICH implementation, you should do as little as possible. In particular, avoid anything that changes the external state of the program, such as opening files, reading standard input or writing to standard output.

来自MPI_FINALIZE

All processes must call this routine before exiting. The number of processes running after this routine is called is undefined; it is best not to perform much more than a return rc after calling MPI_Finalize.

和:

The MPI standard requires that MPI_Finalize be called only by the same thread that initialized MPI with either MPI_Init or MPI_Init_thread.

因此在您的特定情况下,所有进程都分配数组并打印它。

And is there any way to store the output 1 2 in the array without actually sending the data from one process to another?

彼此之间没有处理发送消息。正在发生的事情(非常非正式地)是 MPI 启动程序的完整副本 per 进程,还包括数组的分配 int arr[2];.

如果你想只分配一个进程,让我们说 rank = 0 的进程然后做:

...
if(myrank == 0){
 
   int arr[2];
}

我个人更喜欢做以下,声明一个指针:

int *arr = NULL;

并且只在需要它的进程上分配它:

if(myrank == 0){
  arr = malloc(sizeof(int) * 2);
  ...
}