Skip to content
Snippets Groups Projects
pingpong.cpp 814 B
Newer Older
  • Learn to ignore specific revisions
  • Ondrej Meca's avatar
    Ondrej Meca committed
    
    #include "mpi.h"
    #include <unistd.h>
    
    #define INLOOP 0
    #define FINISH 1
    
    int main(int argc, char **argv) {
    	MPI_Init(&argc, &argv);
    
    	int rank, size;
    	MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    	MPI_Comm_size(MPI_COMM_WORLD, &size);
    
    	int counter = 0;
    	int COUNT = 1;
    	int SOURCE = (rank + size - 1) % size;
    	int TARGET = (rank + 1) % size;
    	int TAG = 0;
    
    	if (rank == 0) { // initialize loop
    		MPI_Send(&counter, COUNT, MPI_INT, TARGET, TAG, MPI_COMM_WORLD);
    	}
    
    	while (true) {
    		MPI_Status status;
    		MPI_Recv(&counter, COUNT, MPI_INT, SOURCE, TAG, MPI_COMM_WORLD, &status);
    
    		if (status.MPI_TAG == INLOOP) {
    			printf("rank %d: counter: %d\n", rank, counter++);
    			usleep(500000);
    		}
    		if (TAG == INLOOP) {
    			MPI_Send(&counter, COUNT, MPI_INT, TARGET, TAG, MPI_COMM_WORLD);
    		}
    	}
    
    	MPI_Finalize();
    	return 0;
    }