我有一些代码可以将2D数组打印到标准输出。问题在于运行时,每个进程都会写入输出并且数据会重叠,使其无法使用。
如何在MPI中构建关键部分,以便只有一个进程进入我显示输出的部分?
我正在使用OpenMPI。
我有一些代码可以将2D数组打印到标准输出。问题在于运行时,每个进程都会写入输出并且数据会重叠,使其无法使用。
如何在MPI中构建关键部分,以便只有一个进程进入我显示输出的部分?
我正在使用OpenMPI。
使用 MPI_Barriers 进行分离。
rank = 0;
while (rank < total_processes) {
if (myrank == rank) {
printf ("Array printed by rank: %d\n", myrank);
print_array();
fflush (stdout);
}
rank ++;
MPI_Barrier ();
}
#include<iostream>
#include"mpi.h"
void main(int args, char **argv) {
int i;
int nitems = 5 ;
int totalnodes, mynode;
double *array;
int trap_key = 0;
MPI_Status status;
MPI_Init(&args, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &totalnodes);
MPI_Comm_rank(MPI_COMM_WORLD, &mynode);
array = new double[nitems];
for (i = 0; i < nitems; i++)
array[i] = double(i);
if (mynode != trap_key) //this will allow only process 0 to skip this stmt
MPI_Recv(&trap_key, 1, MPI_INT, mynode - 1, 0, MPI_COMM_WORLD, &status);
//here is the critical section
cout << "I am Process: " << mynode << endl;
for (i = 0; i < nitems; i++)
cout << "array[" << i << "] =" << array[i] << endl;
if(mynode != totalnodes - 1) // this will allow only the last process to
//skip this
MPI_Send(&trap_key, 1, MPI_INT, mynode + 1, 0, MPI_COMM_WORLD);
MPI_Finalize();
}
请编译此代码,然后在调试文件目录中打开cmd,输入:mpiexec yourprojectname.exe
简单来说,我所做的就是用接收和发送操作将关键部分包围起来,这样每个进程都会等待前一个进程完成。
rank
的值。 :) - suszterpatt