MPI练习 群式通讯函数-MPI_Gather以及MPI_Scatter的使用

多个员工被模拟为多个相关进程,编写进行资薪的排序,要求非0(根)进程未知其他员工的工资。只需要获知自己的工资排名。

工资暂且用 —100以内的随机数

实现过程如下, 每个进程赋予一个随机的工资数, MPI_Gather使用收集数据到进程0, 排序后在MPI_Scatter其排名给其他进程。

在这里插入图片描述

#include <stdio.h>
#include "mpi.h"
#include <stdlib.h>
#include<malloc.h>
typedef struct
{
    int val;
    int rank;
}DATATYPE;
int main(int argc, char** argv)
{
    int rank , size;
    DATATYPE* rbuf;
    DATATYPE sdata;
    MPI_Comm comm = MPI_COMM_WORLD;
    MPI_Init(&argc,  &argv);
    MPI_Comm_size(comm, &size);
    MPI_Comm_rank(comm, &rank);
    MPI_Status status;
    
    srand(time(NULL) + rank);
    
    printf("process %d has ", rank);
    sdata.val = rand()%100;
    sdata.rank = rank;
    printf("%d\n", sdata.val);
    if (rank  ==  0)
    {
        rbuf = (DATATYPE*)malloc(sizeof(DATATYPE) * size);
    }
    
    
    MPI_Gather(&sdata, 1, MPI_2INT, rbuf, 1, MPI_2INT,0, comm);
    int sbuf[size];
    if(rank == 0)
    {
        int i, j;
        for(i = 0; i < size -1; i++)
            for(j = 0; j < size - 1 - i; j++)
        {
            DATATYPE tmp;
            if(rbuf[j].val < rbuf[j+1].val)
            {
                tmp = rbuf[j+1];
                rbuf[j+1] = rbuf[j];
                rbuf[j] = tmp;
            }
        }
        printf("the sequence is: \n");
        for(i = 0; i < size; i++)
            printf("num:%d from process %d\n", rbuf[i].val, rbuf[i].rank);
        
        for(i = size - 1; i >= 0; i--)
        {
            sbuf[rbuf[i].rank] = i;
        }
        
    }
    int num;
    MPI_Scatter(sbuf, 1, MPI_INT, &num, 1, MPI_INT, 0, comm);
    printf("process %d, receives: %d\n", rank, num);
    MPI_Finalize();
    return 0;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_38023259/article/details/88826575
mpi