问题描述
我写一些这样的代码:
void main(int argc, char **argv ) {
char message[20];
int i, rank, size, type=99;
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if(rank == 0) {
strcpy_s(message, "Hello, world");
for (i=1; i<size; i++)
MPI_Send(message, 13, MPI_CHAR, i, type, MPI_COMM_WORLD);
} else {
MPI_Recv(message, 20, MPI_CHAR, 0, type, MPI_COMM_WORLD, &status);
}
printf( "Message from process =%d : %.13s\n", rank, message);
MPI_Finalize();
}
我的输出是随机排序的.例如:
My output is random ordered. For example:
Message from process = 4 : Hello, world
Message from process = 2 : Hello, world
Message from process = 0 : Hello, world
Message from process = 1 : Hello, world
Message from process = 3 : Hello, world
但是我想这样做:
Message from process = 0 : Hello, world
Message from process = 1 : Hello, world
Message from process = 2 : Hello, world
Message from process = 3 : Hello, world
Message from process = 4 : Hello, world
我尝试了一些代码,但是仍然可以处理随机顺序.
I try some code, but still process random order.
我更改了代码.现在,每个进程都等待其前任发出的消息.但仍会处理随机排序的输出.我写了MPI_Wait,但它不起作用.
I change my code. Now, every process wait its message from predecessor. But still processes outputs random ordered. I write MPI_Wait but it is not working.
if(rank == 0) {
strcpy_s(message, "Hello, world");
printf( "Message from process =%d : %.13s\n", rank, message);
MPI_Isend(message, 13, MPI_CHAR, rank + 1, type, MPI_COMM_WORLD, &request);
MPI_Wait(&request, &status);
} else {
MPI_Recv(message, 20, MPI_CHAR, (rank - 1) % size, type, MPI_COMM_WORLD, &status);
printf( "Message from process =%d : %.13s\n", rank, message);
if(rank < (size - 1)){
MPI_Isend(message, 13, MPI_CHAR, (rank + 1) % size, type, MPI_COMM_WORLD, &request);
MPI_Wait(&request, &status);
}
}
我希望有人能帮助我.谢谢.
I hope some people help me. Thanks.
推荐答案
默认情况下,printf
语句将由碰巧首先遇到该处理器的任何处理器(而不是排名顺序)进行评估.如果您绝对必须按等级顺序进行操作,则可以尝试以下操作:
By default, the printf
statement will be evaluated by whichever processor happens to run into it first, not by order of rank. If you absolutely have to do it in order of rank, then you can try something like:
for(i = 0; i < size; i++) {
if(i == rank) {
printf("Message from process =%d : %.13s\n", rank, message);
}
MPI_Barrier(MPI_COMM_WORLD);
}
这会循环遍历每个等级,只允许打印当前等级,而其他所有人都按下MPI_Barrier
并被迫等待.不过请记住,这不是可扩展的方法.
This loops through each rank and only allows the current rank to print, while everyone else hits MPI_Barrier
and is forced to wait. Keep in mind, though, that this is not a scalable approach.
这篇关于没有排序输出,使用MPI并行编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!