我一直在做一个MPI项目,在这个项目中,从站都把数据发回主站。出于某种原因,如果我连续执行 2 次发送,主服务器只会接收数据。这很奇怪,我认为它导致了我遇到的其他一些奇怪的问题。知道是什么原因造成的吗?我认为第一次发送是发送某种垃圾数据或其他东西。不过,发送的代码行完全相同。
编辑:下面的代码...
if (numProcs > 0)
MPI_Barrier( MPI_COMM_WORLD ) ; //only wait if there are other processes to wait for
if (rank != 0)
{
MPI_Send(handArray, 10, MPI_DOUBLE, 0, TAG_HAND, MPI_COMM_WORLD);
MPI_Send(handArray, 10, MPI_DOUBLE, 0, TAG_HAND, MPI_COMM_WORLD);
}
//8. After the main loop the master process receives and sums together the hand counts array
// from each slave process.
else
{
int activeProcs = numProcs - 1;
getHandsFromSlaves( activeProcs, handArray );
然后主版继续打印一些数据...
这是getHands FromSlaves方法。请注意,我也尝试使用阻止调用,也遇到了同样的问题。
void getHandsFromSlaves( int& activeCount, double handTotals[10] ){
static MPI_Request request;
static int msgBuff, recvFlag;
static double handBuff[10];
MPI_Status status;
while (activeCount > 0)
{
if( request )
{
// Already listening for a message
// Test to see if message has been received
MPI_Test( &request, &recvFlag, &status );
//cout << "TAG: " << status.MPI_TAG << " SOURCE: "<< status.MPI_SOURCE << " ERROR: " << status.MPI_ERROR << endl;
if( recvFlag )
{
// Message received
if( status.MPI_TAG == TAG_HAND )
{
cout << "Hand Received!" << endl;
for(int m = 0; m < 10; ++m)
{
handTotals[m] += handBuff[m];
}
activeCount--;
}
else
{
//error report... what happened?
cout << "TAG: " << status.MPI_TAG << " SOURCE: "<< status.MPI_SOURCE << " ERROR: " << status.MPI_ERROR << endl;
}
// Reset the request handle
request = 0;
}
}
if( !request && activeCount > 0 )
// Start listening again
MPI_Irecv(&handBuff, 10, MPI_DOUBLE, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &request);
}
}
好吧,您可能正在尝试处理太多的消息,因为您的request
变量在进入getHandsFromSlaves()
例程时未定义。 由于在输入时,request
几乎肯定是非零的,因此即使您没有发布Irecv
,您也会立即尝试MPI_Test
消息。
事实上,这里发布的代码摘录有很多非常奇怪的地方。 为什么局部变量static
? 为什么要在MPI_Test()
上实现自己的 busywait 而不是使用 MPI_Wait()
? 如果您在接收之间没有做任何有用的事情,为什么还要使用非阻塞接收? 事实上,如果你只是总结所有的数组,为什么你做单独的点对点接收而不是做一个MPI_Reduce()
?
以下更短的代码似乎可以执行您上面尝试执行的操作:
#include <stdio.h>
#include <mpi.h>
int main (int argc, char **argv) {
int rank, numProcs;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &numProcs);
double handArray[10];
double handTotal[10];
for (int i=0; i<10; i++)
handArray[i] = rank + i;
if (rank == 0) // Since apparently rank 0 doesn't do anything
{
for (int i=0; i<10; i++)
handArray[i] = 0;
}
MPI_Reduce(handArray, handTotal, 10, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
if (rank == 0) {
printf("Hand Totals= n");
for (int i=0; i<10; i++)
printf(" %lf ", handTotal[i]);
printf("n");
}
MPI_Finalize();
}