// use MPI_Bsend to send several messages in buffered mode // note that the total sum of memory(buffer) must be allocated first, // otherwise it will produce error #include #include #define M 3 // the number of times of sending messages int main( int argc, char** argv ) { int n, i; int rank; int size; int *buf; int *abuf; int blen; int ablen; MPI_Status status; MPI_Init( &argc, &argv ); MPI_Comm_size( MPI_COMM_WORLD, &size ); MPI_Comm_rank( MPI_COMM_WORLD, &rank ); if( size != 2 ) { if( rank == 0 ) { printf("Error: 2 processes required\n"); fflush(stdout); } MPI_Abort(MPI_COMM_WORLD, MPI_ERR_OTHER ); } if( rank == 0 ){ blen = M * (sizeof(int) + MPI_BSEND_OVERHEAD); buf = (int*) malloc(blen); MPI_Buffer_attach(buf, blen); printf("attached %d bytes\n", blen); fflush(stdout); for(i = 0; i < M; i ++) { printf("starting send %d ...\n", i); fflush(stdout); n = i; MPI_Bsend(&n, 1, MPI_INT, 1, i, MPI_COMM_WORLD ); printf("complete send %d\n", i); fflush(stdout); sleep(1); } MPI_Buffer_detach(&abuf, &ablen); printf("detached %d bytes\n", ablen); free(abuf); } else { for(i = M - 1; i >= 0; i --) { printf("starting recv %d ...\n", i); fflush(stdout); MPI_Recv(&n, M, MPI_INT, 0, i, MPI_COMM_WORLD, &status ); printf("complete recv: %d. received %d\n", i, n); fflush(stdout); } } MPI_Finalize(); return 0; }