用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字

芙蓉妹妹    -  云代码空间

——

多进程共同计算一组数据的最大值

2019-04-20|852阅||

摘要:data = (int*)malloc(sizeof(int)*num); avge = num / size; start = rank * avge; end = rank == size - 1? num - 1: start + avge - 1;

#include<stdio.h>
#include "mpi.h"
int main(int argc, char** argv){
    MPI_Init(&argc, &argv);
    MPI_Comm comm = MPI_COMM_WORLD;
    int rank, size, max, mmax, start, end, avge, *data, num, i;
    MPI_Comm_rank(comm, &rank);
    MPI_Comm_size(comm, &size);
    MPI_Status status;
    if(rank == 0){
        printf("please input the num of data :\n");
        scanf("%d",&num);
        for(i = 1; i < size; i++)
            MPI_Send(&num,1,MPI_INT,i,99,comm);
        data = (int*)malloc(sizeof(int)*num);
        for(i = 0;i < num;i++)
            scanf("%d",&data[i]);
        for(i = 1; i < size; i++)
            MPI_Send(data,num,MPI_INT,i,99,comm);
        avge = num / size;
        max = data[0];
        for(i = 1; i < avge; i++){
            if(data[i] > max)
                max = data[i];
        }
        printf("process %d:satrt- 0 , end- %d ,max- %d.\n",rank, avge -1,max);
        mmax = max;
        for(i = 1; i < size; i++){
            MPI_Recv(&max,1,MPI_INT,i,99,comm,&status);
            //printf("process 0 recv max from process %d\n",i);
            if(max > mmax)
                mmax = max;
        }
        printf("The max is %d\n",mmax);
    }
    else{
        MPI_Recv(&num,1,MPI_INT,0,99,comm,&status);
        //printf("process %d recv %d from process 0\n",rank,num);
        data = (int*)malloc(sizeof(int)*num);
        MPI_Recv(data,num,MPI_INT,0,99,comm,&status);
        //printf("process %d recv data from process 0\n",rank);
        avge = num / size;
        start = rank * avge;
        end = rank == size - 1? num - 1: start + avge - 1;
        max = data[start];
        for(i = start; i<= end; i++){
            if(data[i] > max)
                max = data[i];
        }
        printf("process %d :satrt- %d , end- %d ,max- %d.\n",rank,start, end,max);
        MPI_Send(&max,1,MPI_INT,0,99,comm);
        //printf("process %d send %d to process 0\n", rank,max);
    }
    MPI_Finalize();
    return 0;
}

顶 1踩 1收藏
文章评论
    发表评论

    个人资料

    • 昵称: 芙蓉妹妹
    • 等级: 资深程序员
    • 积分: 1710
    • 代码: 104 个
    • 文章: 25 篇
    • 随想: 0 条
    • 访问: 32 次
    • 关注

    标签

    最新提问

      站长推荐