消息在网络上的两台机器之间传递

Message passing between two machines on a network

本文关键字:两台 机器 之间 网络 消息      更新时间:2023-10-16

问题描述:网络中的两个不同的Unix机器上有两个进程。从一台计算机到另一台机器的最简单方法是什么?我知道IPC有很多方法,但是最小的开销最简单的方法是什么?

在我的情况下,Boost MPI有用吗?我正在使用C 进行实施。

插座。这是一个插座教程。一旦有插座,您也可以使用Boost插座

使用套接字(我建议提升插座)或查看Zeromq。Zeromq实际上可能会更容易,因为它可以保证始终接收完整的消息。

这很简单吗?(使用纯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库是具有大量支持基础架构的复杂代码部分,例如您需要通过专用启动器程序(在大多数情况下mpiexecmpirun)运行代码,并且您不能使用MPI简单地连接两个随机过程(即,您确实确实有通过mpiexec/mpirun启动它们)。