Created
July 9, 2021 13:27
Star
You must be signed in to star a gist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <mpi.h> | |
#include <vector> | |
int main( int argc, char *argv[] ) | |
{ | |
int size, rank; | |
MPI_Init( &argc, &argv ); | |
MPI_Comm_size( MPI_COMM_WORLD, &size ); | |
MPI_Comm_rank( MPI_COMM_WORLD, &rank ); | |
int n = 6; | |
int Tag = 0; | |
int EndTag = 1; | |
MPI_Request request; | |
/// | |
/// iprobe + receive | |
/// | |
auto iprobeRecv = [&rank, &Tag, &EndTag](int source, int tag) | |
{ | |
MPI_Status status; | |
int flag; | |
// rank=sourceからtagメッセージが来ていないかを確認 | |
MPI_Iprobe(source, tag, MPI_COMM_WORLD, &flag, &status); | |
if ( flag == 1 ) | |
{ | |
if ( tag == Tag ) | |
{ | |
// メッセージが来ていたら受信 | |
int progressCount = 0; | |
MPI_Recv(&progressCount, 1, MPI_INT, source, tag, MPI_COMM_WORLD, &status); | |
std::cout << "rank " << rank << " receives from " << source << " job-id " << progressCount << std::endl; | |
} | |
else if ( tag == EndTag ) | |
{ | |
MPI_Recv(NULL, 0, MPI_BYTE, source, tag, MPI_COMM_WORLD, &status); | |
std::cout << "rank " << rank << " receives from " << source << " end_tag" << std::endl; | |
} | |
} | |
return flag; | |
}; | |
/// | |
/// main | |
/// | |
for ( int i = rank; i < n; i += size ) | |
{ | |
// 何かしらのjobをした | |
std::cout << "rank " << rank << " works job " << i << std::endl; | |
if( rank == 0 ) | |
{ | |
// 受信 | |
for ( int source = 1; source < size; source++ ) | |
iprobeRecv(source, Tag); | |
} | |
else | |
{ | |
// 行ったjob-Idiを送信 | |
MPI_Isend(&i, 1, MPI_INT, 0, Tag, MPI_COMM_WORLD, &request); | |
} | |
} | |
/// | |
/// Post Process | |
/// | |
if ( rank > 0 ) | |
{ | |
// jobを終えたworkerはend_tagを送信 | |
MPI_Send(NULL, 0, MPI_BYTE, 0, EndTag, MPI_COMM_WORLD); | |
} | |
else | |
{ | |
for ( int source = 1; source < size; source++ ) | |
{ | |
// end_tagを受け取るまでiprob | |
while ( !iprobeRecv(source, EndTag) ) | |
iprobeRecv(source, Tag); | |
} | |
} | |
MPI_Finalize(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment