您的位置:首页 > 编程语言

MPI_Probe-Dynamically allocate memory

2015-08-21 06:42 531 查看
某些情况下,接收者不知道消息尺寸,此时当然可以用一个足够大的空间去接收,但我们可以用MPI_Probe去首先探测消息尺寸,然后再分配相应空间,然后再正式接收消息,可以认为MPI_Probe和MPI_Recv很类似,只是不真正执行接收操作

MPI_Probe(
int source, //source rank, or MPI_ANY_SOURCE (integer)
int tag, //tag value or MPI_ANY_TAG (integer)
MPI_Comm comm, //communicator (handle)
MPI_Status *status)


例子,设进程1随机决定发送给其它进程的数据个数,其他进程需要先探测真实尺寸,然后接收:

#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
int main(int argc, char** argv) {
MPI_Init(NULL, NULL);

int nProcs,Rank;
int i;
MPI_Status status;
MPI_Comm_size(MPI_COMM_WORLD, &nProcs);
MPI_Comm_rank(MPI_COMM_WORLD, &Rank);

int NumToBeSent;

if (Rank == 0) {

const int MaxNum = 6000;
std::vector<double> Data;
srand(time(NULL));

for(i=0;i<MaxNum;i++)Data.resize(MaxNum);
for(i=0;i<MaxNum;i++)Data[i] = i;

for(i=1;i<nProcs;i++)
{
NumToBeSent = rand() % MaxNum;
MPI_Send(&Data[0],NumToBeSent, MPI_DOUBLE, i, 0, MPI_COMM_WORLD);
printf("0 sent %d numbers to %d\n", NumToBeSent,i);
}
}
else {

MPI_Probe(0, 0, MPI_COMM_WORLD, &status);
//When MPI_Probe returns, the size information is included, the MPI_Get_count function can extract size information
MPI_Get_count(&status, MPI_DOUBLE, &NumToBeSent);
// Now we can allocate suitable memory for the receive buffer
double* recvbuf = (double*)malloc(sizeof(double) * NumToBeSent);
// Now the message can be received properly
MPI_Recv(recvbuf, NumToBeSent, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD,&status);
printf("%d Received %d Data From 0.\n", Rank, NumToBeSent);
free(recvbuf);
}
system("pause");
MPI_Finalize();
}


一个执行输出如下(设4个进程):

0 sent 5646 numbers to 1

0 sent 430 numbers to 2

0 sent 1365 numbers to 3

1 received 5646 Data From 0

2 received 430 Data From 0

3 received 1365 Data From 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息