【发布时间】:2021-06-22 13:57:55
【问题描述】:
我正在尝试使用 MPI(赋值)在 C 中构建具有多维数组的程序。
下面的程序运行但在 2 个输出行中给出了错误的值。 a 是一个多维数组。我不包含任何 0 值。但是第二个输出行是partial process: values are 0 and 0。为什么打印0值,我的a数组中没有0值。
这是我的基本程序
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
// size of array
#define n 6
int a[6][2] = { {2,3},{51,55},{88,199},{335,34534},{678,683},{98,99} };
// Temporary array for slave process
int a2[1000][2];
int main(int argc, char* argv[])
{
int pid, np,
elements_per_process,
n_elements_recieved;
// np -> no. of processes
// pid -> process id
MPI_Status status;
// Creation of parallel processes
MPI_Init(&argc, &argv);
// find out process ID,
// and how many processes were started
MPI_Comm_rank(MPI_COMM_WORLD, &pid);
MPI_Comm_size(MPI_COMM_WORLD, &np);
// master process
if (pid == 0) {
int index, i;
elements_per_process = n / np;
// check if more than 1 processes are run
if (np > 1) {
// distributes the portion of array
// to child processes to calculate
// their partial sums
for (i = 1; i < np - 1; i++) {
index = i * elements_per_process;
MPI_Send(&elements_per_process,
1, MPI_INT, i, 0,
MPI_COMM_WORLD);
MPI_Send(&a[index],
elements_per_process,
MPI_INT, i, 0,
MPI_COMM_WORLD);
}
// last process adds remaining elements
index = i * elements_per_process;
int elements_left = n - index;
MPI_Send(&elements_left,
1, MPI_INT,
i, 0,
MPI_COMM_WORLD);
MPI_Send(&a[index],
elements_left,
MPI_INT, i, 0,
MPI_COMM_WORLD);
}
// master process add its own sub array
for (i = 0; i < elements_per_process; i++)
printf("master process: values are %d and %d\n", a[i][0], a[i][1]);
// collects partial sums from other processes
int tmp;
for (i = 1; i < np; i++) {
MPI_Recv(&tmp, 1, MPI_INT,
MPI_ANY_SOURCE, 0,
MPI_COMM_WORLD,
&status);
int sender = status.MPI_SOURCE;
}
}
// slave processes
else {
MPI_Recv(&n_elements_recieved,
1, MPI_INT, 0, 0,
MPI_COMM_WORLD,
&status);
// stores the received array segment
// in local array a2
MPI_Recv(&a2, n_elements_recieved,
MPI_INT, 0, 0,
MPI_COMM_WORLD,
&status);
// calculates its partial sum
int useless_fornow = -1;
for (int i = 0; i < n_elements_recieved; i++) {
printf("partial process: values are %d and %d \n", a2[i][0], a2[i][1]);
}
// sends the partial sum to the root process
MPI_Send(&useless_fornow, 1, MPI_INT,
0, 0, MPI_COMM_WORLD);
}
// cleans up all MPI state before exit of process
MPI_Finalize();
return 0;
}
这是输出:
部分过程:值为678和683
部分过程:值为0和0
主进程:值为 2 和 3
主进程:值为 51 和 55
部分过程:值为 88 和 199
部分过程:值为0和0
我正在使用此命令mpiexec.exe -n 3 Project1.exe 使用 3 个进程运行它
【问题讨论】:
标签: c performance parallel-processing mpi hpc