寫完 Hello World 之後,MPI 學習的下一步就是讓 process 之間真正交換資料。點對點通訊只需要一對函式:MPI_Send 負責送、MPI_Recv 負責收。以下這支程式讓 0 號 process 送一段字串給 1 號 process,是最小可行的驗證範例。
#include <mpi.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
int _tmain(int argc, _TCHAR* argv[])
{
int myid, numprocs;
int namelen;
char processor_name[MPI_MAX_PROCESSOR_NAME];
char buff[100];
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
MPI_Get_processor_name(processor_name, &namelen);
fprintf(stderr,
"\nHello World! Process %d of %d on %s\n",
myid, numprocs, processor_name);
memset(buff, 0, 100);
if (myid == 0)
{
strcpy(buff, "0 to 1");
MPI_Send(buff, strlen(buff), MPI_CHAR, 1, 99, MPI_COMM_WORLD);
fprintf(stderr, "\nsend:%s", buff);
}
else
{
MPI_Status sta;
if (myid == 1)
{
MPI_Recv(buff, 20, MPI_CHAR, 0, 99, MPI_COMM_WORLD, &sta);
fprintf(stderr, "\nrecv:%s", buff);
}
}
MPI_Finalize();
if (myid == 0)
{
printf("\nPress a key and exit.\n");
getch();
}
return 0;
}
用 MPIRun 啟動時,mpirun -np x $(TargetPath) 裡的 x 必須大於 1。這支程式的邏輯依賴至少兩個 process 才能成立:只有一個 process 時,rank 0 會送資料給 rank 1,但 rank 1 不存在,MPI_Send 將永遠等不到對應的接收而阻塞。
MPI_Send(buffer, count, datatype, dest, tag, communicator)
MPI_CHAR。MPI_COMM_WORLD。MPI_Recv(buffer, count, datatype, source, tag, communicator, status)
前五個參數與 MPI_Send 對應:source 是來源 rank(此例為 0)。最後多出的 status 用來接收這則訊息的 metadata——實際收到的位元組數、來源、tag 等,可透過 MPI_Get_count 進一步取出。
這裡有個實務上的細節值得留意:發送端用 strlen(buff) 送出實際長度,接收端卻寫了固定值 20。這在 MPI 中是允許的——接收緩衝區只要「大 enough」即可,實際抵達的長度會記在 status 裡。因為 buff 事先被 memset 清零,字串後面的部分仍是 '\0',列印時不會出問題。但若接收端收到未清零的記憶體,就可能印出多餘的垃圾字元,這類 bug 在 MPI 程式中相當常見。
MPI_Send 與 MPI_Recv 都是阻塞式呼叫。這意味著:
這也是 MPI 最經典的死結來源:如果兩個 process 都先呼叫 MPI_Send 再呼叫 MPI_Recv,而訊息量又大到超過系統緩衝容量,雙方都會卡在 Send 上等對方來收,永遠走不到 Recv。這支範例之所以安全,是因為只有 rank 0 送、rank 1 收,方向單向,不會形成循環等待。
處理這類問題有幾種正規做法:調整收送順序(一送一收交錯)、改用 MPI_Sendrecv 一次完成雙向交換、或使用非阻塞的 MPI_Isend / MPI_Irecv 搭配 MPI_Wait。
程式中 rank 1 的判斷寫成外層 else 內再嵌一個 if (myid == 1),效果等於 else if (myid == 1)。這樣寫沒錯,但若 process 數大於 2,rank 2 以上的 process 就會什麼都不做直接走到 MPI_Finalize。在這個教學範例中無妨,實務上則應明確處理每一種 rank 的行為,避免有 process 提早退出導致其他 process 的 Send 永遠等不到對手。
點對點通訊熟了之后,可以往兩個方向延伸:集合通訊(MPI_Bcast 廣播、MPI_Reduce 歸約、MPI_Gather 收集)能大幅簡化多 process 協作的程式碼;衍生資料型別(MPI_Type_contiguous、MPI_Type_vector)則能一次傳送非連續的記憶體區塊,省去手工拆包組包。兩者都是實際 HPC 程式的主力工具。