MPI第四站 -- linux上 学习从接收信息中拿出来更多的信息

版权声明:博主原创文章属私人所有,未经允许 不可转发和使用 https://blog.csdn.net/a1066196847/article/details/89527389

main.cpp

#include "iostream"
#include "mpi.h"
#include "stdlib.h"
using namespace std;

void get_status(){
    // 初始化
    MPI_Init(NULL, NULL);
    // 定义进程号 rank 秩
    int world_rank;
    MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
    // 找到一共有多少个 进程
    int world_size;
    MPI_Comm_size(MPI_COMM_WORLD, &world_size);

    const int MAX_NUMBERS = 100;
    int numbers[MAX_NUMBERS];
    int number_amount;

    if(world_rank == 0){
        //设置下随机数
        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;
        //可以接收最多 MAX_NUMBERS 个数据,从process 0中
        MPI_Recv(numbers, MAX_NUMBERS, MPI_INT, 0, 87, MPI_COMM_WORLD, &status);  //这里面的87应该是88,如果不是88的话,就只会0进程进行运行,不会打印else if里面的东西

        // 收到信息之后,检查下信息状态,并且看看实际中我们真的接收到多少的数据
        MPI_Get_count(&status, MPI_INT, &number_amount);

        //打印信息
        cout << "1 received "<<number_amount << " numbers from 0.Message source = " <<status.MPI_SOURCE <<" tag = "<<status.MPI_TAG;
    }
}

int main() {
    get_status();
}


CMakeLists.txt和前面一样   

执行代码是

mpic++ main.cpp -o main.out   

mpirun -np 2  ./main.out

最终的打印结果是

注释:如果在执行的时候,mpirun -np 1  ./main.out

就会报错

MPI_Send(100): Invalid rank has value 1 but must be nonnegative and less than 1

可以看这篇文章进行求解

https://stackoverflow.com/questions/35669614/mpi-send100-invalid-rank-has-value-1-but-must-be-nonnegative-and-less-than-1

猜你喜欢

转载自blog.csdn.net/a1066196847/article/details/89527389