MPI广播和减少

时间:2019-07-14 03:43:55

标签: c multiprocessing mpi

我在下面有此代码。 当我用mpiexec -n 2运行它时 我在控制台日志中得到了类似The input sequence is as follows: 0 1 2 3的输出 我正在尝试获取0 2 6 12的输出序列 这是forloop中PartialResult的加法 这是forloop的结果,我在每个进程中都得到了此结果,因此当我在2个进程中运行时,它被打印两次。

Partial result in forloop: 0 
Partial result in forloop: 1 
Partial result in forloop: 3 
Partial result in forloop: 6 

我想添加它们,以便输出序列(当rank == 0时)返回0 2 6 12。在MPI_Reduce步骤之后可以实现吗?

下面是整个C代码。

int main(void)

{
    int my_rank, comm_sz;
    int i;
    int Count = 4;
    int Number[4];
    int PartialResult = 0;
    int Result;

    MPI_Init(NULL, NULL);

    MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);


    if(my_rank == 0)
    {
        printf("The input sequence is as follows: \n");

        for (i = 0; i < Count; i++)
        {
            Number[i] = i;
            printf("%d ", Number[i]);
        }

        printf("\n");
    }

    // Process 0 sends data to all of the processes
    MPI_Bcast(Number, Count, MPI_INT, 0, MPI_COMM_WORLD);

    for (i = 0; i < Count; i++)
    {
        Number[i] += my_rank;
        PartialResult += Number[i];
        printf("\n");
        printf("Partial result in forloop: %d \n", PartialResult);

    }
    MPI_Reduce(&PartialResult, &Result, 1, MPI_INT, MPI_PROD, 0, MPI_COMM_WORLD);
    printf("partial result after reduce: %d \n", PartialResult);    

    // Print out the result 
    if (my_rank == 0) {
        printf("\n");
        for (i = 0; i < Count; i++) {
            printf("\n");
            printf("\n");
            printf("Result[i]: %d \n", Result[i]);

        } 
    }

    MPI_Finalize();

    return 0;
}

0 个答案:

没有答案