/** * non-blocking.c * * Demonstrates using the MPI_Iprobe function to check if a message is * available. If it is, then the message is received and status printed. If not, * then the main process (rank 0) keeps incrementing its counter. * * NOTE: Ranks other than 0 and 1 will be ignored. * * Compile: mpicc -g -Wall non-blocking.c -o non-blocking * Run: mpirun -n 2 ./non-blocking */ #include #include #include #include #include int main(void) { MPI_Init(NULL, NULL); /* Get the rank of this process */ int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 0) { int random; unsigned long counter = 0; int flag; while (true) { MPI_Iprobe(MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &flag, MPI_STATUS_IGNORE); if (flag == 1) { MPI_Recv(&random, 1, MPI_INT, 1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); printf("Received number: %d; counter: %lu\n", random, counter); } counter++; } } else if (rank == 1) { /* I will send a random number to rank 3 after sleeping a random number * of seconds */ int random; int sleep_time; while (true) { random = rand(); sleep_time = rand() % 3; sleep(sleep_time); MPI_Send(&random, 1, MPI_INT, 0, 0, MPI_COMM_WORLD); } } MPI_Finalize(); return 0; }