c - 使用 MPI 收集和组织 vector

标签 c parallel-processing mpi

我想从 double 数组中收集数据并同时组织它们。假设我们有 2 个 MPI 等级:

if(rank == 0)
   P = {0,1,4,5,8,9};
else
   P = {2,3,6,7,10,11}; 

我如何收集位于 P 中的信息并按顺序定位它们,即: master 中的 P 应该包含 P= [0 1 2. ...9 10 11]

我可以按原样收集 P,然后在 root 中重新组织它,但是这种方法效率不高,因为 P 是增加。我已经尝试创建一个 MPI_Type_vector 但是我还没有成功。有什么想法吗?

最佳答案

这在一定程度上取决于您所说的“按顺序”是什么意思。如果您的意思是,如上例所示,每个 vector 都由数据 block 组成,并且您希望这些 block 以固定的已知顺序交错,是的,您当然可以这样做。 (这个问题也可以理解为询问你是否可以在收集的过程中进行排序;这更难。)

你有正确的方法;您希望按原样发送数据,但将数据接收到由处理器分解的指定 block 中。在这里,您要接收的数据类型如下所示:

MPI_Datatype vectype;
MPI_Type_vector(NBLOCKS, BLOCKSIZE, size*BLOCKSIZE, MPI_CHAR, &vectype);

也就是说,对于给定处理器的输入,您将把它接收到大小为 BLOCKSIZENBLOCKS block 中,每个 block 由许多处理器分隔 block 大小。事实上,你可以接受那种类型;但是,要收集到该类型,您需要设置范围,以便将来自每个处理器的数据收集到正确的位置:

MPI_Datatype gathertype;
MPI_Type_create_resized(vectype, 0, BLOCKSIZE*sizeof(char), &gathertype);
MPI_Type_commit(&gathertype);

调整大小的原因在例如 this answer 中给出。 ,也可能在本网站的其他地方。

将这些放在示例代码中可以得到以下结果:

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

int main(int argc, char **argv) {

    int rank, size;

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

    const int BLOCKSIZE=2;      /* each block of data is 2 items */
    const int NBLOCKS  =3;      /* each task has 3 such blocks */

    char locdata[NBLOCKS*BLOCKSIZE];
    for (int i=0; i<NBLOCKS*BLOCKSIZE; i++)
        locdata[i] = 'A' + (char)rank;  /* rank 0 = 'AAA..A'; rank 1 = 'BBB..B', etc */

    MPI_Datatype vectype, gathertype;
    MPI_Type_vector(NBLOCKS, BLOCKSIZE, size*BLOCKSIZE, MPI_CHAR, &vectype);
    MPI_Type_create_resized(vectype, 0, BLOCKSIZE*sizeof(char), &gathertype);
    MPI_Type_commit(&gathertype);

    char *globaldata = NULL;
    if (rank == 0) globaldata = malloc((NBLOCKS*BLOCKSIZE*size+1)*sizeof(char));

    MPI_Gather(locdata, BLOCKSIZE*NBLOCKS, MPI_CHAR,
               globaldata, 1, gathertype,
               0, MPI_COMM_WORLD);

    if (rank == 0) {
        globaldata[NBLOCKS*BLOCKSIZE*size] = '\0';
        printf("Assembled data:\n");
        printf("<%s>\n", globaldata);
        free(globaldata);
    }

    MPI_Type_free(&gathertype);
    MPI_Finalize();

    return 0;
}

运行给出:

$ mpirun -np 3 ./vector
Assembled data:
<AABBCCAABBCCAABBCC>
$ mpirun -np 7 ./vector
Assembled data:
<AABBCCDDEEFFGGAABBCCDDEEFFGGAABBCCDDEEFFGG>

关于c - 使用 MPI 收集和组织 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23392525/

相关文章:

c - mpi中的MPI_Probe和MPI_Get_count有什么区别

c++ - MPI 发送/接收错误

php - 是否可以从 linux 服务器的 php 中调用 C 库中的函数?

c++ - 寻找单图像 HDR 算法

C fscanf 输入验证

c++ - 并行化 SVD 计算 c++

c - c 中带有内联 asm 的宏存在格式问题

r - 对于不同的 Redis 服务器构建,doRedis 在 Windows 8 x64 中返回错误

c++ - 并行 vector 调整大小不加速

algorithm - 如何生成信号以停止分布式模型中其他进程的执行