版权声明:博主原创文章属私人所有,未经允许 不可转发和使用 https://blog.csdn.net/a1066196847/article/details/89553414
main.cpp
#include "iostream"
#include "mpi.h"
#include "stdlib.h"
using namespace std;
void check_before_rece(){
MPI_Init(NULL, NULL);
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
if(world_size != 2){
cout << "proesses must be equals to 2"<<endl;
MPI_Abort(MPI_COMM_WORLD, 1);
}
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
int number_amount;
if(world_rank == 0){
const int MAX_NUMBERS = 100;
int numbers[MAX_NUMBERS];
//设置下随机数
srand(22);
//从MAX_NUMBERS范围中,找到一个整数
number_amount = (rand()/(float)RAND_MAX) * MAX_NUMBERS;
//发送
MPI_Send(numbers, number_amount, MPI_INT, 1, 88, MPI_COMM_WORLD);
cout<<"0 sent "<<number_amount <<" numbers to 1 "<<endl;
}else if(world_rank == 1){
MPI_Status status;
//定义一个邮件,来接收收到的信息
MPI_Probe(0, 88, MPI_COMM_WORLD, &status);
// 从接收的信息里拿到一些信息,比如接收数据的count等
MPI_Get_count(&status, MPI_INT, &number_amount);
// 申请一个大小为number_amount的数组,用来存储申请到的数据
int *number_buf = new int[number_amount];
MPI_Recv(number_buf, number_amount, MPI_INT, 0, 88, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
cout << "1 received "<<number_amount << " numbers from 0.Message source = " <<status.MPI_SOURCE <<" tag = "<<status.MPI_TAG;
//
delete [] number_buf;
}
MPI_Finalize();
}
int main() {
// 尝试动态接收信息
// get_status();
// 在接收前,先拿到信息的count数目,然后动态分配内存
check_before_rece();
}
mpic++ main.cpp -o main.out
mpirun -np 2 ./main.out