这够简单吗? (使用纯 MPI 标准调用,没有任何第三方库,如 Boost.MPI)
#include <string>
#include <iostream>
#include <mpi.h>
using namespace std;
int main (int argc, char **argv) {
// Initialise the MPI library
MPI_Init(&argc, &argv);
int rank, size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (size != 2) {
if (rank == 0)
cout << "ERROR: You must run this program with 2 processes" << endl;
MPI_Abort(MPI_COMM_WORLD, 0);
}
if (rank == 0) {
// Rank 0 sends the message
string hi = "Hi!";
MPI_Send((void*)hi.c_str(), hi.length()+1, MPI_CHAR,
1, 0, MPI_COMM_WORLD);
}
else {
// Rank 1 receives the message
// Probe for a message and get its actual size
MPI_Status status;
MPI_Probe(0, 0, MPI_COMM_WORLD, &status);
int len;
MPI_Get_count(&status, MPI_CHAR, &len);
// Allocate buffer space for the message and receive it
char *message = new char[len];
MPI_Recv(message, len, MPI_CHAR,
0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
cout << "Rank 1 received: " << message << endl;
delete [] message;
}
MPI_Finalize();
return 0;
}
用mpic++ -o mpihi.exe mpihi.cc编译并执行:
$ mpiexec -np 2 ./mpihi.exe
Rank 1 received: Hi!
如果消息的长度预先固定,代码可以简化。可以使用Boost.MPI 进一步简化它,但我从未使用过它,所以我无法为您提供示例。
MPI 的优点在于它有保证的消息传递以及它抽象互连细节的方式。您可以通过向mpiexec 提供适当的选项来更改两个 MPI 进程的位置。如果两个进程都放在同一个物理节点上,则共享内存将用于传递消息。如果放在不同的节点上,就会用到一些网络机制。
当然,这一切都取决于您的需求。 MPI 库是具有大量支持基础设施的复杂代码片段,例如您需要通过专门的启动程序运行您的代码(在大多数情况下是mpiexec 或mpirun),并且您不能使用 MPI 来简单地连接两个随机进程(即您真的有来启动它们通过mpiexec/mpirun)。