wiki:mpich/collective_communication/demo2

Source code

/* Program:
 *   由使用者輸入一整數,再由 root node 將些整數發送給底下 nodes,
 *   每個 nodes 將收到的整數印出。
 * History:
 *   2008-07-24 BETA
 */


#include <stdio.h>
#include <mpi.h>
main (int argc, char **argv)
{
  int i = 0;
  int myid, numprocs;
  MPI_Init(&argc, &argv);
  MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
  MPI_Comm_rank(MPI_COMM_WORLD, &myid);

  /* 這邊先印出所有 nodes 的整數 i 初始狀態 */
  printf("[Node %d] i = %d \n", myid, i);

  /* node 0 (root) 會要求使用者輸入一個 INT 的整數 */
  if (myid == 0)
  {
    printf("Please input a INT number >>");
    scanf("%d", &i);
  }

  /* node 0 (root) 會將所有 nodes 的 i 的值設為使用者所輸入的數 */
  MPI_Bcast(&i, 1, MPI_INT, 0, MPI_COMM_WORLD);

  /* 所有的 nodes 在此同步,以確認 node 0 (root) 已將 i 送給所有 nodes */
  MPI_Barrier(MPI_COMM_WORLD);

  printf("[Node %d] i = %d \n", myid, i);

  MPI_Finalize();
}

Result

Last modified 16 years ago Last modified on Jul 24, 2008, 12:06:13 PM

Attachments (2)

Download all attachments as: .zip