c - 如何从进程中打印某些内容而不与其他进程重叠?

标签 c parallel-processing mpi hpc barrier

我编写了一个 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_SendMPI_Recv。可能类似于进程等待 MPI_Recv 等待另一个进程发送一条消息,表明该进程刚刚完成打印其矩阵部分。例如,有 4 个进程:

进程1等待进程0的消息,进程2等待进程1的消息,很快。进程0打印矩阵的一部分并将消息发送到进程1,进程1以相同的方式进行。但同样,您最好将整个矩阵发送到进程 0 并让该进程将矩阵打印到控制台。

关于c - 如何从进程中打印某些内容而不与其他进程重叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66211492/

相关文章:

创建自己的 C 函数库

c++ - 我们可以有多少级别的指针?

c - 摆脱基于文件的通信

c# - .Net 4.0 并行 foreach 循环无法在 "production"应用程序中生成新线程

ssh - 配置 MPI hostsfile 以使用多个用户身份

c++ - 使用 mpi 将矩阵写入单个 txt 文件

c - 一些 C 浮点常量没有意义

c - 从并行数组打印收据

multithreading - 如何在Matlab中对进程强制使用计时器

c - 更新 c 中的局部 vector 条目