2017-02-14 132 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(); 

}