我编写了一个 MPI 代码,该代码正在使用 16 个进程运行,并且我正在打印 4x4 矩阵作为每个进程的输出:
printf("\n This is the output of %d\n",myrank);
for(int i=0;i<count;i++)
{
for(int j=0;j<count;j++)
{
printf("%f ",m[i][j]);
}
printf("\n");
}
但问题是每个进程的输出都会与其他进程混合。像这样——
This is the output of 3
0.750000 0.750000 0.750000 0.500000
This is the output of 9
1.000000 1.000000 1.000000 1.000000
1.000000 1.000000 1.000000
1.000000 1.000000 1.000000 0.750000
1.000000 1.000000 1.000000 0.750000 1.000000
1.000000 1.000000 1.000000 1.000000
1.000000 1.000000 1.000000 1.000000
1.000000 1.000000 1.000000 0.750000
如何防止此类行为?
最佳答案
I have written an MPI code which I am running using 16 processes and I am printing 4x4 matrix as output from each of those process.
这不是 MPI 的使用方式,实际上是一般 IMO 中的并行性。进程之间协调将输出打印到控制台将大大降低并行版本的性能。
大多数时候,最好只让一个进程负责将输出打印到控制台(通常是主进程即具有rank的进程= 0
)。
尽管如此,您可以使用 MPI_Barrier 尝试类似以下的操作,像这样:
int rank;
MPI_Comm_rank (MPI_COMM_WORLD, &rank); /* get current process id */
...
MPI_Barrier(MPI_COMM_WORLD);
if(rank == /** the rank of the process that will print the output **/)
{
// printing the data to the output
}
MPI_Barrier(MPI_COMM_WORLD);
对于您的情况:
MPI_Barrier(MPI_COMM_WORLD);
printf("\n This is the output of %d\n",myrank);
MPI_Barrier(MPI_COMM_WORLD);
for(int i=0;i<count;i++)
{
for(int j=0;j<count;j++)
{
printf("%f ",m[i][j]);
}
printf("\n");
}
这至少可以避免输出“这是 3 的输出”
与矩阵的输出混合。
但是请记住(引用 Hristo Iliev 善意提供的评论):
Using barriers like that only works for local launches when (and if) the processes share the same controlling terminal. Otherwise, it is entirely to the discretion of the I/O redirection mechanism of the MPI implementation.
要按顺序打印矩阵需要更复杂的机制,您将使用 MPI_Send
和 MPI_Recv
。可能类似于进程等待 MPI_Recv 等待另一个进程发送一条消息,表明该进程刚刚完成打印其矩阵部分。例如,有 4 个进程:
进程1
等待进程0
的消息,进程2
等待进程1
的消息,很快。进程0
打印矩阵的一部分并将消息发送到进程1
,进程1
以相同的方式进行。但同样,您最好将整个矩阵发送到进程 0
并让该进程将矩阵打印到控制台。
关于c - 如何从进程中打印某些内容而不与其他进程重叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66211492/