简体   繁体   English

MPI:锁定标准输出——一次1个进程?

[英]MPI: Locking the stdout — 1 process at a time?

I want to print out the content of integer array of each processes.我想打印出每个进程的 integer 数组的内容。 Problem is, it's all cluttered because of race condition.问题是,由于比赛条件,一切都很混乱。

What is the simplest solution?什么是最简单的解决方案? I don't want to debug.我不想调试。 I want to show the contents because I'm doing sorting algorithm.我想显示内容,因为我正在做排序算法。 So it's useful to show before and after sort.所以在排序前后显示是很有用的。

I added this in lock.c:我在 lock.c 中添加了这个:

#include <stdio.h>
static int lock=0;   //Don't use if timing execution
void capture(int rank) {
    while(lock!=0);
    lock = 1;
    printf("\nCaptured by %d\n", rank);
}
void release() {
    lock = 0;
}

And call capture() before printing stuff, then release() after printing.并在打印之前调用 capture(),然后在打印后调用 release()。 Yes, it's a semaphore-like hack.是的,这是一个类似信号量的 hack。 But it isn't working, any ideas?但它不起作用,有什么想法吗?

Assuming you're using an MPI which collects all processes' STDOUTs, you can use MPI_Barrier() to enforce the ordering, like so:假设您使用的是收集所有进程的 STDOUT 的 MPI,您可以使用 MPI_Barrier() 来强制执行排序,如下所示:

for( int i = 0; i < size; ++i ) {
    MPI_Barrier( MPI_COMM_WORLD );
    if ( i == rank ) {
         printf( "..." );
    }
 }

Of course, this is inefficient, but it may be a little simpler than arranging to send all the information back to rank 0.当然,这是低效的,但它可能比安排将所有信息发送回 0 级要简单一些。

Assuming you mean the Message Passing Interface, the best approach is to write the output strings to a buffer and send them to the rank 0 process.假设您指的是消息传递接口,最好的方法是将 output 字符串写入缓冲区并将它们发送到 rank 0 进程。 This process should be used not for doing the real work but just for filtering and outputting the output strings.此过程不应用于执行实际工作,而应仅用于过滤和输出 output 字符串。

Leave the other ranks to do the real work.让其他队伍去做真正的工作。 I don't think your above solution will work because i is local to each rank.我认为您的上述解决方案不会起作用,因为我是每个级别的本地人。

You also don't want to use the messaging to stop the individual ranks (until they can output) since they will be unable to do their sorting work in the meantime.您也不想使用消息传递来阻止各个等级(直到他们可以输出),因为他们将无法同时进行排序工作。

Just have each rank 1 through N do it's work and send strings to rank 0. The strings could be of the form "NNN:SSSSSS" where N is the rank and S is the string.只需让 1 到 N 的每个等级都起作用并将字符串发送到等级 0。字符串可以是"NNN:SSSSSS"形式,其中 N 是等级,S 是字符串。 Rank 0 could then filter out specific messages or write different messages to different files, then combine them (sorted) once all the working ranks had shut down.然后 Rank 0 可以过滤掉特定消息或将不同的消息写入不同的文件,然后在所有工作 rank 关闭后将它们组合(排序)。

Each process has its own copy of the variable.每个进程都有自己的变量副本。 So it's not shared and you can't use it for synchronization.所以它不是共享的,你不能用它来同步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM