主进程产生两个工作进程并将 sendbuf 分散给工作者。

master.c

#include "mpi.h"

int main(int argc, char *argv[])
{ 
   int n_spawns = 2;
   MPI_Comm intercomm;

   MPI_Init(&argc, &argv);

   MPI_Comm_spawn("worker_program", MPI_ARGV_NULL, n_spawns, MPI_INFO_NULL, 0, MPI_COMM_SELF, &intercomm, MPI_ERRCODES_IGNORE); 

   int sendbuf[2] = {3, 5};
   int recvbuf; // redundant for master.

   MPI_Scatter(sendbuf, 1, MPI_INT, &recvbuf, 1, MPI_INT, MPI_ROOT, intercomm);

   MPI_Finalize();
   return 0;
}

worker.c

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

int main(int argc, char *argv[])
{  
   MPI_Init(&argc, &argv);

   MPI_Comm intercomm; 
   MPI_Comm_get_parent(&intercomm);

   int sendbuf[2]; // redundant for worker.
   int recvbuf;

   MPI_Scatter(sendbuf, 1, MPI_INT, &recvbuf, 1, MPI_INT, 0, intercomm);
   printf("recvbuf = %d\n", recvbuf);

   MPI_Finalize();
   return 0;
}

执行

mpicc master.c -o master_program
mpicc worker.c -o worker_program
mpirun -n 1 master_program