【问题标题】:How to print something from processes without other processes overlapping it?如何在没有其他进程重叠的情况下从进程中打印一些东西?
【发布时间】:2021-05-18 13:03:37
【问题描述】:

我编写了一个 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 

如何防止这种行为?

【问题讨论】:

    标签: c parallel-processing mpi hpc barrier


    【解决方案1】:

    我编写了一个 MPI 代码,我正在使用 16 个进程运行它,我 我正在打印 4x4 矩阵作为每个进程的输出。

    这不是 MPI 的使用方式,实际上是一般 IMO 中的并行性。进程之间将输出打印到控制台的协调会大大降低并行版本的性能。

    大多数时候最好让一个进程负责将输出打印到控制台(通常是 master 进程 ie, 进程与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");
    }
    

    这至少可以避免输出 "This is the output of 3" 与矩阵的输出混合。

    但请记住(引用自 Hristo Iliev 友情提供的评论):

    使用这样的障碍仅适用于本地发布时(并且如果) 这些进程共享相同的控制终端。否则就是 完全由 MPI 的 I/O 重定向机制决定 实施。

    要按顺序打印矩阵需要更复杂的机制,您可以使用MPI_SendMPI_Recv。可能类似于进程在 MPI_Recv 上等待另一个进程发送一条消息,表明该进程刚刚完成打印其部分矩阵。例如,有 4 个进程:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 1970-01-01
      • 2012-07-08
      • 2015-04-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多