這份範例示範如何用 MPI 最基礎的回代(back substitution)手法,把一個以上三角矩陣表示的方程組分散到多個程序上平行求解。核心思路是:0 號程序負責把每一列方程式分派給對應的程序,每個程序只保留自己那一列的係數與右端常數,然後由未知量下標最大的程序開始,逐次算出解並用廣播散播給其他程序,其他程序收到後就地更新自己的右端項。
#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
#define ROOT 0
#define TAG 0
int main(int argc, char *argv[]) {
float matrix[][4] = {{2,3,4,5}, // the upper triangular matrix representing a equation set
{0,2,3,4},
{0,0,2,3}};
int xcnt = 3; // count of x
int self, size, tag = 0;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &self);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Request r;
MPI_Status s;
MPI_Datatype MPI_VEC;
MPI_Type_vector(xcnt + 1, 1, 1, MPI_FLOAT, &MPI_VEC);
MPI_Type_commit(&MPI_VEC);
float* equation = (float*)malloc((xcnt + 1) * sizeof(float));
float xs, xr;
if (0 == self) { // send each process the corresponding equation
// parallel send and copy
MPI_Issend(matrix[1], 1, MPI_VEC, 1, TAG, MPI_COMM_WORLD, &r);
for (int i = 0; i <= xcnt; ++i) {
equation[i] = matrix[0][i];
}
MPI_Wait(&r, &s);
for (int i = 2; i < size; ++i) {
MPI_Ssend(matrix[i], 1, MPI_VEC, i, TAG, MPI_COMM_WORLD);
}
} else {
MPI_Recv(equation, 1, MPI_VEC, ROOT, TAG, MPI_COMM_WORLD, &s);
}
for (int i = xcnt - 1; i >= 0; --i) {
if (i == self) {
xs = equation[xcnt] / equation[i];
printf("x%d = %f \n", self, xs);
MPI_Bcast(&xs, 1, MPI_FLOAT, i, MPI_COMM_WORLD);
} else {
MPI_Bcast(&xs, 1, MPI_FLOAT, i, MPI_COMM_WORLD);
if (i > self) {
equation[xcnt] -= equation[i] * xs;
}
}
}
free(equation);
MPI_Finalize();
return 0;
}
xcnt + 1 個 float,用 MPI_Type_vector 定義成 MPI_VEC,一次就能傳一整列,省去逐元素搬運。MPI_Issend 把第 1 列丟出去,同時自己把第 0 列複製進本地緩衝,接著 MPI_Wait 等待傳送完成,再迴圈 MPI_Ssend 分派其餘列,讓傳輸與本地運算重疊。for 從 xcnt - 1 遞減,保證被依賴的未知量先算完;每算出一個解就以該程序為 root 做 MPI_Bcast,其他程序只在 i > self 時更新右端項。MPI_Recv。