不安全的 MPI 非阻塞通信示例?

A not safe MPI non-blocking communication example?

本文关键字:通信 MPI 不安全      更新时间:2023-10-16

我正在程序内实现MPI非阻塞通信。我在MPI_Isend man_page上看到,上面写着:

非阻塞发送调用指示系统可能开始将数据从发送缓冲区复制出来。在调用非阻塞发送操作后,发送方不应修改发送缓冲区的任何部分,直到发送完成。

我的代码是这样的:

// send messages
if(s > 0){
MPI_Requests s_requests[s];
MPI_Status   s_status[s];
for(int i = 0; i < s; ++i){
// some code to form the message to send
std::vector<doubel> send_info;
// non-blocking send
MPI_Isend(&send_info[0], ..., s_requests[i]);
}
MPI_Waitall(s, s_requests, s_status);
}
// recv info
if(n > 0){    // s and n will match
for(int i = 0; i < n; ++i){
MPI_Status status;
// allocate the space to recv info
std::vector<double> recv_info;
MPI_Recv(&recv_info[0], ..., status)
}
}

我的问题是:我是否修改了发送缓冲区,因为它们位于内部大括号中(循环完成后send_info向量被杀死(?因此,这不是一种安全的通信模式吗?虽然我的程序现在运行良好,但我仍然被怀疑。感谢您的回复。

在这个例子中,我想强调两点。

第一个是我质疑的问题:发送缓冲区在MPI_Waitall之前被修改。原因是吉尔斯说的。并且解决方案可以在for loop之前分配一个大的缓冲区,并在循环完成后使用MPI_WaitallMPI_Wait放入循环中。但后者相当于在性能意义上使用MPI_Send

但是,我发现如果您只是简单地转移到阻止发送和接收,像这样的通信方案可能会导致死锁。它类似于经典的死锁:

if (rank == 0) {
MPI_Send(..., 1, tag, MPI_COMM_WORLD);
MPI_Recv(..., 1, tag, MPI_COMM_WORLD, &status);
} else if (rank == 1) {
MPI_Send(..., 0, tag, MPI_COMM_WORLD);
MPI_Recv(..., 0, tag, MPI_COMM_WORLD, &status);
}

解释可以在这里找到。

我的程序可能会导致类似的情况:所有调用MPI_Send的处理器都是死锁。

所以我的解决方案是使用一个大的缓冲区并坚持非阻塞通信方案。

#include <vector>
#include <unordered_map>
// send messages
if(s > 0){
MPI_Requests s_requests[s];
MPI_Status   s_status[s];
std::unordered_map<int, std::vector<double>> send_info;
for(int i = 0; i < s; ++i){

// some code to form the message to send
send_info[i] = std::vector<double> ();
// non-blocking send
MPI_Isend(&send_info[i][0], ..., s_requests[i]);
}
MPI_Waitall(s, s_requests, s_status);
}
// recv info
if(n > 0){    // s and n will match
for(int i = 0; i < n; ++i){
MPI_Status status;
// allocate the space to recv info
std::vector<double> recv_info;
MPI_Recv(&recv_info[0], ..., status)
}
}