Advertisement
Guest User

Untitled

a guest
Nov 2nd, 2011
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.05 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <mpi.h>
  4. #include <unistd.h>
  5.  
  6. const int tag = 42;         /* Message tag */
  7.   int   id, ntasks, source_id, err, i;
  8.   MPI_Status status;
  9.   char msg[80];                /* Message array */
  10.  
  11. int main(int argc, char *argv[]) {
  12.  
  13.  
  14.   err = MPI_Init(&argc, &argv); /* Initialize MPI */
  15.   if (err != MPI_SUCCESS) {
  16.     printf("MPI_init failed!\n");
  17.     exit(1);
  18.   }
  19.  
  20.   err = MPI_Comm_size(MPI_COMM_WORLD, &ntasks); /* Get nr of tasks */
  21.   if (err != MPI_SUCCESS) {
  22.     printf("MPI_Comm_size failed!\n");
  23.     exit(1);
  24.   }
  25.  
  26.   err = MPI_Comm_rank(MPI_COMM_WORLD, &id);    /* Get id of this process */
  27.   if (err != MPI_SUCCESS) {
  28.     printf("MPI_Comm_rank failed!\n");
  29.     exit(1);
  30.   }
  31.  
  32.   MPI_Errhandler_set(MPI_COMM_WORLD, MPI_ERRORS_RETURN);
  33.  
  34.   /* Check that we run on at least two processors */
  35.   if (ntasks < 2) {
  36.     printf("You have to use at least 2 processors to run this program\n");
  37.     MPI_Finalize();        /* Quit if there is only one processor */
  38.     exit(0);
  39.   }
  40.  
  41.   /* Process 0 (the receiver) does this */
  42.   if (id == 0) {
  43.     for (i=1; i<ntasks; i++) {
  44.       mpi_recv_msg();
  45.     }
  46.   }
  47.  
  48.   /* Processes 1 to N-1 (the senders) do this */
  49.   else {
  50.     mpi_send_msg(id);
  51.   }
  52.  
  53.   err = MPI_Finalize();          /* Terminate MPI */
  54.   if (err != MPI_SUCCESS) {
  55.     printf("Error in MPI_Finalize!\n");
  56.     exit(1);
  57.   }
  58.   if (id==0) printf("Ready\n");
  59.   exit(0);
  60. }
  61.  
  62. void mpi_send_msg(int id){
  63.   sleep(id);
  64.   int length;
  65.   MPI_Get_processor_name(msg, &length);
  66.   err = MPI_Send(msg, length, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
  67.   if (err != MPI_SUCCESS) {
  68.     printf("Process %i: Error in MPI_Send!\n", id);
  69.   }
  70. }
  71.  
  72. void mpi_recv_msg(){
  73.  
  74.   int length;
  75.   MPI_Get_processor_name(msg, &length);
  76.   err = MPI_Recv(msg, 80, MPI_CHAR, MPI_ANY_SOURCE, tag, MPI_COMM_WORLD, \
  77.          &status);
  78.   if (err != MPI_SUCCESS) {
  79.     printf("Error in MPI_Recv!\n");
  80.   }
  81.   source_id = status.MPI_SOURCE;
  82.   printf("Hello World from process %d running on %s\n", source_id, msg);
  83.  
  84. }
  85.  
  86.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement