C语言,使用MPI Reduce函数,让进程0找到所有进程的等级总和

时间:2018-07-20 04:50:22

标签: c mpi

我编写这段代码来尝试使用C MPI来找到等级的总和,这在下面给了我这个错误。

我似乎无法找到问题所在,有人知道我做错了什么吗?

我能够将整数X从进程0传递到1并进行广播,但是对于MPI_Sum,它表示我存在分段错误(11)并给出了错误。

我应该如何解决这个问题?

[gauss:31436] *** Process received signal ***

[gauss:31436] Signal: Segmentation fault (11)

[gauss:31436] Signal code: Invalid permissions (2)

[gauss:31436] Failing at address: 0x400960

[gauss:31436] [ 0] /lib64/libpthread.so.0(+0xf370)[0x2aaaaafae370]

[gauss:31436] [ 1] /cm/shared/apps/openmpi/gcc/64/1.10.3/lib64/openmpi/mca_pml_ob1.so(mca_pml_ob1_recv+0xc9)[0x2aaab0e38349]

[gauss:31436] [ 2] /cm/shared/apps/openmpi/gcc/64/1.10.3/lib64/libmpi.so.12(MPI_Recv+0x13c)[0x2aaaaad337bc]

[gauss:31436] [ 3] lab2[0x400b21]

[gauss:31436] [ 4] /lib64/libc.so.6(__libc_start_main+0xf5)[0x2aaaab1dcb35]

[gauss:31436] [ 5] lab2[0x400989]

[gauss:31436] *** End of error message ***



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

int main(int argc, char* argv[])
{
    int my_rank;
    int msgtag = 0;
    int x;
    int my_rank_n = 0;
    int sum_rank;
    int p;
    MPI_Status *status;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
    MPI_Comm_size(MPI_COMM_WORLD, &p);
    for (int i = 0; i < p; i++)
    {
            if (my_rank == 0)
            {
                    x = 10;
                    MPI_Send(&x, 1, MPI_INT, 1, msgtag, MPI_COMM_WORLD);
            }
            else if (my_rank == 1)
            {
                    MPI_Recv(&x, 1, MPI_INT, 0, msgtag, MPI_COMM_WORLD, status);
            }

            MPI_Bcast(&x, 1, MPI_INT, msgtag, MPI_COMM_WORLD);
    }

    if(my_rank == 2)
    {
            printf("X is %d\n",x);
    }



     for (int i = 0; i < p; i++)
    {
            my_rank_n = my_rank;
            MPI_Reduce(&my_rank_n, &sum_rank, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
    }

    if(my_rank == 0)
    {
            printf("Sum of Rank is %d\n", sum_rank);
    }

MPI_Finalize();
return 0;
}

1 个答案:

答案 0 :(得分:1)

错误出在MPI_Recv()中,您没有正确使用status参数。

应该是

MPI_Status status;
MPI_Recv(..., &status);