wiki:mpich/point_to_point/demo3

Version 4 (modified by wade, 16 years ago) (diff)

--

Source code

/* Program:
 *   每個 node 將訊息傳送給 node 0,由,node 0 統一印出
 * History:
 *   2008-06-12 BETA
 *   2008-06-17 更改顯示方式,並增加註解
 */

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

main(int argc, char **argv)
{
  int myrank, i, numprocs;
  char message[20];
  MPI_Status status;
  MPI_Init(&argc, &argv);
  MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
  MPI_Comm_rank(MPI_COMM_WORLD, &myrank);

  /* Node 0 will do the following */
  if(myrank == 0)
  {
    /* receive messages from other nodes */
    for(i = 1; i < numprocs; i++)
    {
      MPI_Recv(message, 20, MPI_CHAR, i, 99, MPI_COMM_WORLD, &status);
      printf("[Node 0] << 「%s」[Node %d] \n", message, status.MPI_SOURCE);
    }
  }

  /* other Nodes will do the following */
  if(myrank != 0)
  {
    /* send node's rank to Node 0 */
    sprintf(message, "[%d]", myrank);
    MPI_Send(message, 20, MPI_CHAR, 0, 99, MPI_COMM_WORLD);
    printf("[Node %d]「%s」 >> [Node 0]\n", myrank, message);
  }
  MPI_Finalize();
}

Result

Attachments (1)

Download all attachments as: .zip