2017-02-25 32 views
1

我正在嘗試執行MPI_Gatherv函數CMPI_Gatherv:在根數組中收到的垃圾值

根據我的節目,每一個過程包括根應該創建大小等於(過程秩+ 1),這將保持過程中的所有單元秩的局部陣列。

然後將此本地數組收集到根的rcv_array中。

不知何故,我得到垃圾值。 有人能告訴我我做錯了什麼? 此外,我是MPI新手,難以理解MPI_Gatherv的顯示rcv_count

我的代碼:

#include<stdio.h> 
#include<mpi.h> 
#include<stdlib.h> 

int sum(int); 

int main(int argc, char **argv){ 

    int proc_count, proc_rank, root = 0; 
    int *localdata = NULL; 
    int *rcv_array = NULL; 
    int *disp = NULL; 
    int *rcv_count = NULL; 

    MPI_Init(&argc, &argv); 
    MPI_Comm_size(MPI_COMM_WORLD, &proc_count); 
    MPI_Comm_rank(MPI_COMM_WORLD, &proc_rank); 

    if(proc_rank == root){ 
     rcv_array = malloc((sum(proc_count)+1) * sizeof(int)); 
     rcv_count = malloc(proc_count * sizeof(int)); 
     disp = malloc(proc_count * sizeof(int)); 
     rcv_count[0] = 1; 
     disp[0] = 0; 

     for(int i=1; i<proc_count; i++){ 
      rcv_count[i] = i+1; 
      disp[i] = rcv_count[i-1] + disp[i-1]; 
     } 
    } 

    localdata = malloc(proc_rank * sizeof(int)); 
    for(int i=0; i<=proc_rank; i++) 
     localdata[i]=proc_rank; 

    MPI_Gatherv(&localdata, proc_rank+1, MPI_INT, rcv_array, rcv_count, disp, MPI_INT, root, MPI_COMM_WORLD); 

    if(proc_rank == root){ 
     printf("Elements gathered from each process rank wise:\n\n"); 
     for(int i=0; i<sum(proc_count)+1; i++){ 
      printf("-%d-", rcv_array[i]); 
     } 
     printf("\n"); 
    } 


    MPI_Finalize(); 
    return 0; 
} 

int sum(int n){ 
    int total = 0; 

    for(int i=1; i<=n; i++) 
     total+=i; 

    return total; 
} 

回答

0

三個小問題:

  1. 你說你要創建大小的本地陣列等於(進程的等級+ 1),但你只能做localdata = malloc(proc_rank * sizeof(int)); 只需malloc((proc_rank + 1) * sizeof(int));來代替。

  2. 作爲MPI_Gatherv的第一個參數,您使用&localdata。這是指針的地址,改用指針本身localdata

  3. sum(proc_count)+1(用於打印和分配),實際上是一個太多。

否則你很好去。特別是棘手的位移/偏移計算看起來很好。