MPI中的关键部分?

问题描述 投票:12回答:2

我有一些代码要打印一个二维数组到标准输出,问题是当我运行它时,每个进程都会向输出写数据,数据重叠,使其无法使用。

我如何在MPI中建立一个关键部分,使一次只有一个进程进入显示输出的部分?

我使用的是OpenMPI。

parallel-processing distributed mpi critical-section
2个回答
19
投票

用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 ();
}

0
投票
#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。

所以简单的说,我所做的就是在关键部分包围着接收和发送操作,这样每个进程都会等待前一个进程完成。

© www.soinside.com 2019 - 2024. All rights reserved.