MPI_Gather到char数组

时间:2016-02-08 14:35:26

标签: c parallel-processing mpi

我正在尝试使用MPI编写一个精心设计的hello world程序。这个想法是根进程向其他进程发送消息,然后其他进程向根包含其进程ID发送消息。所以我想将几个字符数组发送到根进程并最终打印出来。

问题是我没有设法将所有消息收集到根进程中的变量中。我只得到编译错误或不需要的输出。我觉得我在操作char数组时犯了一些基本错误......如果你能帮助我,我会很高兴的!

到目前为止的代码:

// Hello world using MPI
#include <stdio.h>
#include <math.h>
#include <mpi.h>
#include <string.h>

int main(int argc, char **argv){
    // Define useful global constants
    int my_id, root_process, num_procs, rc;
    MPI_Status status;
    char[] final_message;    // <---- How should I define final message? Can I do this in another way?

    // Let master process be process 0
    root_process = 0;

    // Now, replicate this process to create parallel processes:
    rc = MPI_Init(&argc, &argv);

    // Find out MY process ID and how many processes were started:
    rc = MPI_Comm_rank(MPI_COMM_WORLD, &my_id);
    rc = MPI_Comm_size(MPI_COMM_WORLD, &num_procs);

    // Broadcast master's message to slaves
    char message1[20];
    strcpy(message1, "Hello, World!");
    rc = MPI_Bcast(&message1, 14, MPI_CHAR, root_process, MPI_COMM_WORLD);

    // TEST: Each slave now displays message1 along with which process it is.
    //printf("I'm process %i, the message is: %.13s \n",my_id,message1);

    // Now the master collects a return message from each slave, including the process ID.
    char message2[31];
    char message22[2];
    strcpy(message2, "Master, I'm process number ");// %i \n",&my_id ); //28
    sprintf(message22,"%d\n",my_id);
    strcat(message2,message22);
    rc = MPI_Gather(message2, 1, MPI_CHAR, final_message, 1, MPI_CHAR, root_process, MPI_COMM_WORLD);

    // Display the message collected by the master. 
    printf(final_message);

    // Close down this process
    rc = MPI_Finalize();
}

0 个答案:

没有答案