2017-02-14 130 views
0

我讀過關於mpi,我有興趣使用函數MPI_Gather。如何正確使用MPI_Gather?

現在我這樣做,但它不工作:

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

char *funcion (char *a) { 
    sprintf(a, "asdfa%u", 2); 
} 

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

    MPI_Init(&argc, &argv); 
    int rank; 
    MPI_Comm_rank(MPI_COMM_WORLD, &rank); 

    char *parcial = malloc(5*sizeof(char)); 
    char *total; 

    if (rank == 0) { 
     total = malloc(15*sizeof(char)); 
     parcial = "aaaaa"; 
    } 
    else if (rank == 1) { 
     parcial = "bbbbb"; 
    } 
    else if (rank == 2) { 
     parcial = "ccccc"; 
    } 

    MPI_Gather(parcial,5,MPI_CHAR,total,15,MPI_CHAR,0,MPI_COMM_WORLD); 

    if (rank == 0) { 
     printf("%s",total); 
    } 

    MPI_Finalize(); 

} 

除了打印「aaaaabbbbbccccc」的它僅打印「AAAAA」。

我在做什麼錯?

+0

我忘了評論,我與選項-NP 3 – Sergio

+0

執行它。如果你想添加一些問題,只需使用'edit'底部按鈕問題的左邊。 – Zulan

回答

1

recvcount參數指定的任意單個元素的數量,而不是總數。因此,您應該使用:

MPI_Gather(parcial,5,MPI_CHAR,total,5,MPI_CHAR,0,MPI_COMM_WORLD); 

請注意,您對C中字符串的理解從根本上是錯誤的。

首先,每個C字符串都需要一個額外的字節來終止空字符。因此,您必須分配6/16字節。但是,您不能發送那些空終止符,否則主文件中的字符串將簡單地在第一個終止符處結束。但是,您必須明確設置total[15] = 0才能正確終止字符串。

其次,parcial = "aaaaa"不會將字符串複製到你的malloc「d內存(由strncpy完成),而不是指針被簡單地分配到內存中的不同(不可寫)的一部分,其中"aaaaa\0"存儲。

+0

嗨,很好的解釋!我修正了它,現在正在工作,但我做了這個示例代碼,因爲我想解決一個更大(不是很多)的問題。我認爲我可以使你的解釋後正確工作,但我不能,我不知道爲什麼...我給你鏈接希望你能幫助我:https://stackoverflow.com/questions/42239222/收集字符串與mpi-gather-openmpi-c謝謝:) – Sergio

0

這工作不錯:

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

char *funcion (char *a) { 
    sprintf(a, "asdfa%u", 2); 
} 

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

    MPI_Init(&argc, &argv); 
    int rank; 
    MPI_Comm_rank(MPI_COMM_WORLD, &rank); 

    void *total; 
    void *parcial; 

    if (rank == 0) { 
     parcial = "aaaaa"; 
    } 
    else if (rank == 1) { 
     parcial = "bbbbb"; 
    } 
    else if (rank == 2) { 
     parcial = "ccccc"; 
    } 

    MPI_Gather(parcial,5,MPI_CHAR,total,5,MPI_CHAR,0,MPI_COMM_WORLD); 

    if (rank == 0) { 
     printf("%s",(char*)total); 
    } 

    MPI_Finalize(); 

}