MPI - 如何在主进程和工作进程之间对数组部分进行分区和通信

时间:2017-12-01 22:16:43

标签: c++ parallel-processing mpi

我在执行主/工MPI程序时遇到问题。

目标是让master将整数数组的部分传递给worker,让worker对它们的部分进行排序,然后将数组部分返回到主进程,然后将这些部分组合成finalArray []。

我认为这与我如何在进程之间传递数组部分有关,但我似乎无法想到任何新的尝试。

我的代码:

int compare(const void * a, const void * b) // used for quick sort method
{
    if (*(int*)a <  *(int*)b) return -1;
    if (*(int*)a >  *(int*)b) return 1;
    return 0;
}

const int arraySize = 10000;

int main(int argc, char ** argv)
{
    int rank;
    int numProcesses;

    MPI_Init(&argc, &argv);

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

    const int PART = floor(arraySize / (numProcesses - 1));

    auto start = std::chrono::high_resolution_clock::now(); //start timer

    //================================= MASTER PROCESS =================================
    if (rank == 0)
    {
        int bigArray[arraySize];
        int finalArray[arraySize];

        for (int i = 0; i < arraySize; i++)                                             //random number generator
        {
            bigArray[i] = rand();
        }

        for (int i = 0; i < numProcesses - 1; i++)
        {
            MPI_Send(&bigArray, PART, MPI_INT, i + 1, 0, MPI_COMM_WORLD);               // send elements of the array
        }

        for (int i = 0; i < numProcesses - 1; i++)
        {
            std::unique_ptr<int[]> tmpArray(new int[PART]);

            MPI_Recv(&tmpArray, PART, MPI_INT, i + 1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); //recieve sorted array from workers

            for (int k = 0; k < PART; k++)
            {
                finalArray[PART * i + k] = tmpArray[k];
            }
        }

        for (int m = 0; m < arraySize; m++)
        {
            printf(" Sorted Array:  %d \n", finalArray[m]);                             //print my sorted array
        }
    }

    //================================ WORKER PROCESSES ===============================
    if (rank != 0)
    {
        std::unique_ptr<int[]> tmpArray(new int[PART]);

        MPI_Recv(&tmpArray, PART, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);    //recieve data into local initalized array
        qsort(&tmpArray, PART, sizeof(int), compare);                                   // quick sort
        MPI_Send(&tmpArray, PART, MPI_INT, 0, 0, MPI_COMM_WORLD);                       //send sorted array back to rank 0
    }

    MPI_Barrier(MPI_COMM_WORLD);

    auto end = std::chrono::high_resolution_clock::now();                               //end timer
    std::cout << "process took: "
        << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count()    //prints timer
        << " nanoseconds\n ";

    MPI_Finalize();
    return 0;
}

我是MPI和C ++的新手,所以任何有关此问题的主题的建议都非常有用。我意识到这段代码可能存在许多问题,所以请提前感谢您的帮助。

0 个答案:

没有答案