芙蓉妹妹 - 云代码空间
——
#include <stdio.h> #include <time.h> #include "mpi.h" #include <malloc.h> #include <stdlib.h> typedef struct data{ int val; int rank; }DATA; int main(int argc, char ** argv){ int rank,size,num,order,*rbuf,i,j; DATA *arr; MPI_Comm comm = MPI_COMM_WORLD; MPI_Status status; MPI_Init(&argc,&argv); MPI_Comm_size(comm, &size); MPI_Comm_rank(comm, &rank); srand((int)time(NULL) + rank); num = rand() % 66; if(rank == 0){ rbuf = (int*)malloc(sizeof(int)*size); arr = (DATA*)malloc(sizeof(DATA)*size); } MPI_Gather(&num,1,MPI_INT,rbuf,1,MPI_INT,0,comm); if(rank == 0){ for(i = 0;i < size; i++){ arr[i].val = rbuf[i]; arr[i].rank = i; } DATA mid; for(i = 0; i< size - 1; i++) for(j = 0;j < size-1-i ; j++){ if(arr[j].val < arr[j+1].val){ mid.val = arr[j].val; mid.rank = arr[j].rank; arr[j].val = arr[j + 1].val; arr[j].rank = arr[j + 1].rank; arr[j + 1].val = mid.val; arr[j + 1].rank = mid.rank; } } for(i = 0; i< size; i++){ for(j = 0; j < size; j++){ if(arr[j].rank == i) rbuf[i] = j; } } } MPI_Scatter(rbuf,1,MPI_INT,&order,1,MPI_INT,0,comm); printf("Process %d: my num is %d ,order is %d.\n",rank,num,order); if(rank == 0){ free(rbuf); free(arr); } MPI_Barrier(comm); MPI_Finalize(); return 0; }
for(i = 0; i< size - 1; i++) for(j = 0;j < size-1-i ; j++){ if(arr[j].val < arr[j+1].val){ mid.val = arr[j].val; mid.rank = arr[j].rank; arr[j].val = arr[j + 1].val; arr[j].rank = arr[j + 1].rank; arr[j + 1].val = mid.val; arr[j + 1].rank = mid.rank; } }等所有的进程都运行完,在结束整个函数:
MPI_Barrier(comm);