fork download
  1. #include <stdio.h>
  2. #include <mpi.h>
  3. int main(int argc, char *argv[])
  4. {
  5. const int tag = 42; /* Message tag */
  6. int id, ntasks, source_id, dest_id, err, i;
  7. MPI_Status status;
  8. int msg[2]; /* Message array */
  9.  
  10. err = MPI_Init(&argc, &argv); /* Initialize MPI */
  11. if (err != MPI_SUCCESS)
  12. {
  13. printf("MPI initialization failed!\n");
  14. exit(1);
  15. }
  16. err = MPI_Comm_size(MPI_COMM_WORLD, &ntasks); /* Get nr of tasks */
  17. err = MPI_Comm_rank(MPI_COMM_WORLD, &id); /* Get id of this process */
  18. if (ntasks < 2)
  19. {
  20. printf("You have to use at least 2 processors to run this program\n");
  21. MPI_Finalize(); /* Quit if there is only one processor */
  22. exit(0);
  23. }
  24. if (id == 0)
  25. { /* Process 0 (the receiver) does this */
  26. for (i = 1; i < ntasks; i++)
  27. {
  28. err = MPI_Recv(msg, 2, MPI_INT, MPI_ANY_SOURCE, tag, MPI_COMM_WORLD,
  29. &status); /* Receive a message */
  30. source_id = status.MPI_SOURCE; /* Get id of sender */
  31. printf("Received message %d %d from process %d\n", msg[0], msg[1],
  32. source_id);
  33. }
  34. }
  35. else
  36. { /* Processes 1 to N-1 (the senders) do this */
  37. msg[0] = id; /* Put own identifier in the message */
  38. msg[1] = ntasks; /* and total number of processes */
  39. dest_id = 0; /* Destination address */
  40. err = MPI_Send(msg, 2, MPI_INT, dest_id, tag, MPI_COMM_WORLD);
  41. }
  42.  
  43. err = MPI_Finalize(); /* Terminate MPI */
  44. if (id == 0)
  45. printf("Ready\n");
  46. exit(0);
  47. return 0;
  48. }
Success #stdin #stdout #stderr 0.27s 40812KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "int main"
Execution halted