一般来说,我倾向于避开它们。不要求您使用标签。如果需要在解析消息前获取消息大小,可以使用MPI_Probe。这样您就可以发送不同的消息而不是指定标签。我通常使用标签,因为MPI_Recv 要求您在获取数据之前知道消息大小。如果您有不同的大小和类型,标签可以通过让多个线程或进程侦听不同的子集来帮助您区分它们。标签 1 可以表示 X 类型的消息,而标签 2 将是 Y 类型的消息。此外,它使您能够拥有多个通信“渠道”,而无需创建独特的通信者和组。
#include <mpi.h>
#include <iostream>
using namespace std;
int main( int argc, char* argv[] )
{
// Init MPI
MPI_Init( &argc, &argv);
// Get the rank and size
int rank, size;
MPI_Comm_rank( MPI_COMM_WORLD, &rank );
MPI_Comm_size( MPI_COMM_WORLD, &size );
// If Master
if( rank == 0 ){
char* message_r1 = "Hello Rank 1";
char* message_r2 = "Hello Rank 2";
// Send a message over tag 0
MPI_Send( message_r1, 13, MPI_CHAR, 1, 0, MPI_COMM_WORLD );
// Send a message over tag 1
MPI_Send( message_r2, 13, MPI_CHAR, 2, 1, MPI_COMM_WORLD );
}
else{
// Buffer
char buffer[256];
MPI_Status status;
// Wait for your own message
MPI_Recv( buffer, 13, MPI_CHAR, 0, rank-1, MPI_COMM_WORLD, &status );
cout << "Rank: " << rank << ", Message: " << buffer << std::endl;
}
// Finalize MPI
MPI_Finalize();
}