在哪里初始化数组然后分散它。 MPI_Scatter

Where to initialize array then to scatter it. MPI_Scatter

我需要使用 MPI_Scatter 将数组片段发送到所有进程,然后获取所有元素的总和。我应该在哪里初始化数组然后分散它?在根级别?

如果我在根等级上初始化数组,那么其他等级就不会获得它们的数据。否则我可以为每个人初始化数组(在 if(rank == root)...else 之外),但这意味着我多次创建数组。

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

using namespace std;

int main(int argc, char* argv[])
{
    int size;
    int rank;

    srand(time(NULL));

    MPI_Init(&argc, &argv);

    MPI_Comm_size(MPI_COMM_WORLD, &size);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    int arr_size = size * 2;
    int block = arr_size / (size);

    int* B = new int[block];

    if (rank == 0)
    {
        int* A = new int[arr_size];

        cout << "generated array: " << endl;
        for (int i = 0; i < arr_size; i++)
        {
            A[i] = rand() % 100;
            cout << A[i] << " ";
        }
        cout << endl;

        MPI_Scatter(A, block, MPI_INT, B, block, MPI_INT, 0, MPI_COMM_WORLD);       
    }

    cout << "process " << rank << " received: " << endl;
    for (int i = 0; i < block; i++)
    {
        cout << B[i] << " ";
    }
    cout << endl;

    int local_sum = 0;
    for (int i = 0; i < block; i++)
    {
        local_sum += B[i];
    }
    cout << "sum in process " << rank << " = " << local_sum << endl;
    cout << endl;

    int global_sum;
    MPI_Reduce(&local_sum, &global_sum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);

    if (rank == 0)
    {
        cout << "sum = " << global_sum << endl;
    }

    MPI_Finalize();
    return 0;
}

我得到这样的结果(只有根排名得到了它的数据):

process 1 received:
process 3 received:
-842150451 -842150451
-842150451 -842150451
sum in process 1 = -1684300902
sum in process 3 = -1684300902


process 2 received:
-842150451 -842150451
sum in process 2 = -1684300902

process 0 received:
4 9
sum in process 0 = 13

sum = -757935397
  1. MPI_Scatter() is a collective operation and must hence be invoked by all the ranks.
  2. Declare int *A = NULL; on all ranks and only allocate and populate on rank zero.
int* A = NULL;
int* B = new int[block];

if (rank == 0)
{
    A = new int[arr_size];

    cout << "generated array: " << endl;
    for (int i = 0; i < arr_size; i++)
    {
        A[i] = rand() % 100;
        cout << A[i] << " ";
    }
    cout << endl;
}

MPI_Scatter(A, block, MPI_INT, B, block, MPI_INT, 0, MPI_COMM_WORLD);