mpi消息传递缓冲区乱码

使用openmpi1.4.3版本练习使用MPI编程,写了一个简单的消息传递和接收的小demo,结果输出接收到的信息的时候出现乱码,现象如下:

[chengang@m910 mpi]$ mpirun -n 2 a.out
received: Hello, process 1Àa
                            #:
[chengang@m910 mpi]$ mpirun -n 2 a.out
received: Hello, process 1`Hè:
[chengang@m910 mpi]$ mpirun -n 2 a.out
received: Hello, process 1PbzÆ:
[chengang@m910 mpi]$ mpirun -n 2 a.out
received: Hello, process 1 _™:
[chengang@m910 mpi]$ mpirun -n 2 a.out
received: Hello, process 1À´Î8:

 由此可见,每次运行结果都不一样。

源代码如下:

#include "mpi.h"

int main(int argc, char* argv[])
{
        char message[20];
        int myrank;
        MPI_Status status;
        MPI_Init(&argc, &argv);
        MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
        if(0 == myrank)
        {
                strcpy(message, "Hello, process 1");
                MPI_Send(message, strlen(message), MPI_CHAR, 1, 99, MPI_COMM_WORLD);
        }else if(1 == myrank)
        {
                MPI_Recv(message, 20, MPI_CHAR, 0, 99, MPI_COMM_WORLD, &status);
                printf("received: %s:\n", message);
        }
        MPI_Finalize();
}

 初步猜测在于传递的字符串只有16个字符长度,而缓冲区message有20个字符长度。这样,缓冲区message多余的四个字符空间所存储的字符时没有意义的,所以打印的时候将多余四个字符空间的字符打印出来,导致乱码。针对此猜测,将缓冲区大小设置为刚好字符串的16个字符长度,代码如下:

#include "mpi.h"

int main(int argc, char* argv[])
{
        char message[16];
        int myrank;
        MPI_Status status;
        MPI_Init(&argc, &argv);
        MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
        if(0 == myrank)
        {
                strcpy(message, "Hello, process 1");
                MPI_Send(message, strlen(message), MPI_CHAR, 1, 99, MPI_COMM_WORLD);
        }else if(1 == myrank)
        {
                MPI_Recv(message, 16, MPI_CHAR, 0, 99, MPI_COMM_WORLD, &status);
                printf("received: %s:\n", message);
        }
        MPI_Finalize();
}

 修改之后编译运行,结果如下:

[chengang@m910 mpi]$ mpirun -n 2 a.out
received: Hello, process 1:
[chengang@m910 mpi]$ mpirun -n 2 a.out
received: Hello, process 1:
[chengang@m910 mpi]$ mpirun -n 2 a.out
received: Hello, process 1:

 从结果来看,至少我的猜测还是有一定正确的可能性的。

你可能感兴趣的:(编程)