|
| 1 | +// Author: Wes Kendall |
| 2 | +// Copyright 2011 www.mpitutorial.com |
| 3 | +// This code is provided freely with the tutorials on mpitutorial.com. Feel |
| 4 | +// free to modify it for your own use. Any distribution of the code must |
| 5 | +// either provide a link to www.mpitutorial.com or keep this header in tact. |
| 6 | +// |
| 7 | +// MPI_Send, MPI_Recv example. Communicates the number -1 from process 0 |
| 8 | +// to processe 1. |
| 9 | +// |
| 10 | +#include <mpi.h> |
| 11 | +#include <stdio.h> |
| 12 | +#include <stdlib.h> |
| 13 | +#include <assert.h> |
| 14 | +#include <unistd.h> |
| 15 | +#include <limits.h> |
| 16 | +#include <time.h> |
| 17 | + |
| 18 | +int main(int argc, char** argv) { |
| 19 | + int iteration = 10; |
| 20 | + if (argc > 1) { |
| 21 | + iteration = atoi(argv[1]); |
| 22 | + } |
| 23 | + |
| 24 | + // Initialize the MPI environment |
| 25 | + MPI_Init(NULL, NULL); |
| 26 | + // Find out rank, size |
| 27 | + int world_rank; |
| 28 | + MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); |
| 29 | + int world_size; |
| 30 | + MPI_Comm_size(MPI_COMM_WORLD, &world_size); |
| 31 | + |
| 32 | + // We are assuming at least 2 processes for this task |
| 33 | + if (world_size < 3) { |
| 34 | + fprintf(stderr, "World size must be greater than or equal to 3 for %s\n", argv[0]); |
| 35 | + MPI_Abort(MPI_COMM_WORLD, 1); |
| 36 | + } |
| 37 | + |
| 38 | + // rank 0 wait a while then send messages to rank 1 |
| 39 | + if (world_rank == 0) { |
| 40 | + int number = 0; |
| 41 | + for (int i = 0; i < iteration; i++) { |
| 42 | + sleep(10); |
| 43 | + MPI_Send(&number, 1, MPI_INT, 1, 0, MPI_COMM_WORLD); |
| 44 | + number++; |
| 45 | + MPI_Barrier(MPI_COMM_WORLD); |
| 46 | + printf("Rank 0 have successfully sent %d messages to rank 1\n", i + 1); |
| 47 | + fflush(stdout); |
| 48 | + } |
| 49 | + } else if (world_rank == 1) { |
| 50 | + // rank 1 receive message from 0 first and then 2 |
| 51 | + int number = 0; |
| 52 | + for (int i = 0; i < iteration; i++) { |
| 53 | + int recv_number = -1; |
| 54 | + MPI_Recv(&recv_number, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); |
| 55 | + assert(number == recv_number); |
| 56 | + MPI_Recv(&recv_number, 1, MPI_INT, 2, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); |
| 57 | + assert(number == recv_number); |
| 58 | + number++; |
| 59 | + MPI_Barrier(MPI_COMM_WORLD); |
| 60 | + printf("Rank 1 have successfully received %d messages\n", (i + 1) * 2); |
| 61 | + fflush(stdout); |
| 62 | + } |
| 63 | + } else { |
| 64 | + // rank 2 send messages to rank 1 right away |
| 65 | + int number = 0; |
| 66 | + for (int i = 0; i < iteration; i++) { |
| 67 | + MPI_Send(&number, 1, MPI_INT, 1, 0, MPI_COMM_WORLD); |
| 68 | + number++; |
| 69 | + MPI_Barrier(MPI_COMM_WORLD); |
| 70 | + printf("Rank 2 have successfully sent %d messages to rank 1\n", i + 1); |
| 71 | + fflush(stdout); |
| 72 | + } |
| 73 | + |
| 74 | + } |
| 75 | + MPI_Finalize(); |
| 76 | + return 0; |
| 77 | +} |
0 commit comments