block.c

#include<stdio.h>
#include<mpi.h>
/***********************************************
mpicc -o block block.c
mpirun -np 2 block
***********************************************/

int main( int argc, char *argv[]){
   int numTasks, rank,    rc;

  MPI_Init(&argc, &argv);
  MPI_Comm_size(MPI_COMM_WORLD, &numTasks); //get from -np    
  MPI_Comm_rank(MPI_COMM_WORLD, &rank); //each process's ID
                
   if(rank == 0){    
       char sendChar = 'A';
       char receiveChar;
                 int count = 1;
       int destRank = 1;
       int sourceRank = 1; //MPI_ANY_SOURCE    
       int tagSendMSGID = 6;
       int tagRecvMSGID = 9;
      MPI_Status status;
    
      rc = MPI_Send(&sendChar, count, MPI_CHAR, destRank, tagSendMSGID, MPI_COMM_WORLD);    
      rc = MPI_Recv(&receiveChar, count, MPI_CHAR, sourceRank, tagRecvMSGID, MPI_COMM_WORLD, &status);
        
      printf( "Rank = %d, sendChar = %c, received char =    %c\n", rank, sendChar, receiveChar);
      printf( "Received from task %d with tag %d\n", status.MPI_SOURCE, status.MPI_TAG);
  } else if(rank == 1){
       char sendChar = 'Z';
       char receiveChar;
       int count = 1;
       int destRank = 0;    
       int sourceRank = 0;
       int tagRecvMSGID = 6;
       int tagSendMSGID = 9;
      MPI_Status status;

      rc =    MPI_Recv(&receiveChar, count, MPI_CHAR, sourceRank, tagRecvMSGID, MPI_COMM_WORLD, &status);
                         if(receiveChar == 'A'){
        rc = MPI_Send(&sendChar, count, MPI_CHAR, destRank, tagSendMSGID, MPI_COMM_WORLD);
      }
        
      printf( "Rank = %d, received char = %c, then send char = %c\n", rank, receiveChar, sendChar);
      printf( "Received from task %d with tag %d\n", status.MPI_SOURCE, status.MPI_TAG);
  }
    
    MPI_Finalize();
     return 0;
}
相關文章
相關標籤/搜索