如何将数组分配给多个进程?

时间:2019-05-25 21:13:48

标签: mpi random-walk

我遇到一个问题,我需要将一个数组分配给多个进程,每个进程只能接收两个值,并且进程的大小和数量可能是“奇数或偶数”

我已经使用MPI_Scatter将10个项目的数组分配给5个流程,然后使用MPI_Gather收集了一个流程的结果,并且运行顺利,但是当我遇到3或4个流程时,我陷入了困境,我需要使它动态化有什么可以计算的方法

    #define master 0;
int main(int argc, char * argv[]){
    int const N = 9;
    int competition [N];
    competition[0] = 15;
    competition[1] = 12;
    competition[2] = 16;
    competition[3] = 16;
    competition[4] = 14;
    competition[5] = 19;
    competition[6] = 20;
    competition[7] = 18;
    competition[8] = 17;
    competition[9] = 13;



    int nextStage[5];
    int winnerByAcclamation = 0;
    MPI_Init(NULL,NULL);
    int rank, processes;
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD,&processes);

    /////////define the reciving buffer and itd size
        int const count = 2;            
        int receive_data[count];
    ////////disturbute data
        //determine the winner by acclamation if the size of the array is odd
        if((ARRAYSIZE(competition)% 2 ) != 0){

            for(int i=0; i < ARRAYSIZE(competition); i++){
                if (competition[i] > winnerByAcclamation){
                    winnerByAcclamation = competition[i];
                }
            }

            for(int i=0; i < ARRAYSIZE(competition)-1; i++){
                if (competition[i] != winnerByAcclamation){
                    nextStage[i] = competition[i];
                }
            }
            MPI_Scatter(&nextStage,count,MPI_INT,receive_data,count,MPI_INT,0,MPI_COMM_WORLD);
        }

    /////// determine winner
        //printf("the first value from process %d is %d",rank,receive_data[0]);
        double x = (double)rand() / (double)RAND_MAX;
        int winner;
        if (x < 0.5){
        winner = receive_data[0]+1;
        printf("my rank is %d and hthe winner is %d     \n",rank,winner);
        }else if (x > 0.5){
        winner = receive_data[1]+1;
        printf("my rank is %d and hthe winner is %d     \n",rank,winner);
        }
    ////// gathering the winners
        MPI_Gather(&winner,1,MPI_INT,&winners,1,MPI_INT,0,MPI_COMM_WORLD);
        if (rank == 0){
            winners[5] = winnerByAcclamation;
        for(int i = 0; i < 5; i++){
            printf("%d  ",winners[i]);
        }
        }
        MPI_Finalize();
    return 0;
}

0 个答案:

没有答案