使用MPI_Scatter时出现段故障

时间:2019-10-09 00:58:52

标签: c++ mpi

我对MPI_Scatter有问题。不知道使用它会很热,启动时我的当前程序因段错误而崩溃。

我猜想MPI_Scatter的参数存在问题,特别是在使用正确的运算符(&或*或void)调用时,但我尝试了几乎所有组合,但没有任何帮助。

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

// k = 3, N = 12,  1,2,3, 4,5,6, 7,8,9, 10,11,12

int main(int argc, char **argv) {
    int N, size, myrank;
    int k;
    std::cin >> N;
    std::cin >> k;
    int *mass = new int[N];
    int *recv = new int[k];

    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    MPI_Comm_rank(MPI_COMM_WORLD, &myrank);

    if (myrank == 0) {
        std::cout << "get k and n \n";

        for (int i = 0; i < N; ++i) {
            mass[i] = i;
            std::cout << i << " written\n";
        }
    }

    MPI_Scatter(mass, k, MPI_INT, recv, k, MPI_INT, 0, MPI_COMM_WORLD);

    int sum = 0;
    std::cout << "myrank" << myrank << '\n';
    for (int i = 0; i < k; ++i) {
        std::cout << recv[i] << '\n';
    }

    MPI_Finalize();

    return 0;
}

当我启动这段代码时,它会显示以下内容:

N = 12
k = 3
get k and n 
0 written
1 written
2 written
3 written
4 written
5 written
6 written
7 written
8 written
9 written
10 written
11 written
myrank0
0
1
2
myrank1
myrank3
myrank2
[1570583203.522390] [calc:32739:0]          mpool.c:38   UCX  WARN  object 0x7fe1f08b2f60 was not returned to mpool mm_recv_desc
[1570583203.523214] [calc:32740:0]          mpool.c:38   UCX  WARN  object 0x7f4643986f60 was not returned to mpool mm_recv_desc
[1570583203.524205] [calc:32741:0]          mpool.c:38   UCX  WARN  object 0x7f22535d4f60 was not returned to mpool mm_recv_desc

1 个答案:

答案 0 :(得分:1)

MPI通常会将stdout重定向到等级0,因此Nk没有在其他等级上正确设置。

这是您程序的有效版本

#include <iostream>
#include <cassert>
#include <stdio.h>
#include <mpi.h>

// k = 3, N = 12,  1,2,3, 4,5,6, 7,8,9, 10,11,12

int main(int argc, char **argv) {
    int k, N, size, myrank;
    int *mass;

    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    MPI_Comm_rank(MPI_COMM_WORLD, &myrank);


    if (myrank == 0) {
        std::cout << "get k and n \n";
        std::cin >> N;
        std::cin >> k;
        assert (N >= k*size);
        mass = new int[N];
        for (int i = 0; i < N; ++i) {
            mass[i] = i;
            std::cout << i << " written\n";
        }
    }
    MPI_Bcast(&k, 1, MPI_INT, 0, MPI_COMM_WORLD);

    int *recv = new int[k];

    MPI_Scatter(mass, k, MPI_INT, recv, k, MPI_INT, 0, MPI_COMM_WORLD);

    int sum = 0;
    std::cout << "myrank" << myrank << '\n';
    for (int i = 0; i < k; ++i) {
        std::cout << recv[i] << '\n';
    }

    MPI_Finalize();

    return 0;
}