Skip to content
Snippets Groups Projects
msgexchange.c 1.25 KiB
Newer Older
  • Learn to ignore specific revisions
  • jansik's avatar
    jansik committed
    #include <mpi.h>
    #include <stdio.h>
     
    int main(int argc, char *argv[])
    {
    int rank, nprocs, len, n, sum;
    char   pname[MPI_MAX_PROCESSOR_NAME];
    
    
        MPI_Init(&argc, &argv);
        MPI_Comm_size(MPI_COMM_WORLD,&nprocs);
        MPI_Comm_rank(MPI_COMM_WORLD,&rank);
    
    
        MPI_Get_processor_name(pname,&len);
        printf("Hello world! from rank %d of %d on host %s\n", rank, nprocs,pname);
    
        MPI_Barrier(); //Work for you
    
        if (rank==0) {
            printf("Enter the number to broadcast ");
            scanf("%d",&n);
        }
    
        MPI_Bcast(); //Work: broadcast n from rank 0 to all other ranks
        printf("1, rank %d, n= %d\n",rank,n);
    
        if (rank==1) {
           n=5;
           MPI_Send(); //Work: send n from rank to rank 2 
           printf("2. rank %d, n= %d\n",rank,n);
           MPI_Recv(); //Work: receive  n from rank 2
           printf("3. rank %d, n= %d\n",rank,n);
        }
    
        if (rank==2) {
           MPI_Recv(); //Work: receive n from rank 1
           printf("2. rank %d, n= %d\n",rank,n);
           n=15;
           MPI_Send(); //Work: send n to rank 1
           printf("3. rank %d, n= %d\n",rank,n);
        }
    
        //Work: insert barrier    
    
        sum=0;
        MPI_Reduce(); //Work: Reduce values of n to variable sum, on rank 0.
        printf("4. rank %d, n= %d\n",rank,sum);
    
    
        MPI_Finalize();
    
        return 0;
    }