jeudi 16 décembre 2021

Inizialize random array in C with MPI

I'm new to MPI and wanted to ask if it was possible to initialize an array randomly with MPI without having to go and re-copy the various elements following a Send and Recive, what I was thinking of doing was via a Gather and Scatter process, but I don't know if that's feasible. This is the test with Send and Recive, unfortunately, the rank 0 has to re-copy all the elements.

Can this copy be avoided?

void generateArrayParallel(int arr[], int n, int rank, int nprocs)
{
    int size;
    if (nprocs == 1)
        size = 0;
    else
        size = n / (nprocs - 1);                 
    int leftElements = n - (size * (nprocs - 1)); 

    MPI_Bcast(&size, 1, MPI_INT, 0, MPI_COMM_WORLD);
    MPI_Status status;

    if (rank == 0)
    {
        int *arrRicv = (int *)calloc(size, sizeof(int *));
        srand(rank);

        for (int i = 1; i < nprocs; i++)
            MPI_Send(&arr[(i - 1) * size], size, MPI_INT, i, 1, MPI_COMM_WORLD);

        for (int i = n - leftElements; i < n; i++)
            arr[i] = (int)rand() % 100000;

        for (int i = 1; i < nprocs; i++)
        {
            MPI_Recv(arrRicv, size, MPI_INT, i, 2, MPI_COMM_WORLD, &status);
            for (int j = 0; j < size; j++)
            {
                arr[((i - 1) * size) + j] = arrRicv[j];
            }
        }
        free(arrRicv);
    }
    else
    {
        int *arrRicv = (int *)calloc(size, sizeof(int *));
        MPI_Recv(arrRicv, size, MPI_INT, 0, 1, MPI_COMM_WORLD, &status);
        srand(rank);
        for (int i = 0; i < size; i++)
            arrRicv[i] = (int)rand() % 100000;

        MPI_Send(arrRicv, size, MPI_INT, 0, 2, MPI_COMM_WORLD);
        free(arrRicv);
    }

    }
}





Aucun commentaire:

Enregistrer un commentaire