MPI_Probe-Dynamically allocate memory
2015-08-21 06:42
531 查看
某些情况下,接收者不知道消息尺寸,此时当然可以用一个足够大的空间去接收,但我们可以用MPI_Probe去首先探测消息尺寸,然后再分配相应空间,然后再正式接收消息,可以认为MPI_Probe和MPI_Recv很类似,只是不真正执行接收操作
例子,设进程1随机决定发送给其它进程的数据个数,其他进程需要先探测真实尺寸,然后接收:
一个执行输出如下(设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
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
相关文章推荐
- MPI-Communication modes(通讯模式)
- C和C++ 语言动态内存分配
- C/C++中的二维数组动态内存分配与释放
- 利用libjpeg库压缩成jpg图像,采用动态内存分配 /linux/c/c++
- C风格字符串动态分配和撤销内存报错的问题
- 输入一个长度未知的字符串,用动态分配内存的方法(C语言实现)
- realloc用法
- 动态分配内存(不限长度)
- 三种动态内存分配
- 动态分配内存
- C/C++动态内存分配
- C++学习实战——通过动态分配内存打印杨辉三角
- 数据结构C语言版--动态顺序表的基本功能实现(二)
- 动态分配内存的原理
- Effective C++第三章-资源管理-1
- C++动态内存分配和使用vector创建数组对象
- 指针和动态分配内存 (不定长度数组)------新标准c++程序设计
- C++ Code:动态分配数组内存的六种方法
- 浅析C语言之内存分配函数malloc()、realloc()、calloc()
- 内存分配的两种方法