c++ - 无法编译返回 MPI::Comm 类型对象的函数

标签 c++ mpi communicator

要使用 MPI 运行我的软件,我需要创建一个返回 MPI::COMM_WORLD 的简单方法。

所以在我的类里面,我们有:

#include <mpi.h>
class Parallel{      
    public:

        MPI::Comm getCommunicator(){
            return MPI::COMM_WORLD;
        }
    protected:

    int iproc;
};

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

    Parallel* parallel;
    MPI::Init(argc, argv);
    int my_rank;
    my_rank = parallel->getCommunicator().Get_rank();
    MPI::Finalize();
    return 0;
}

我应该如何实现 getCommunicator() 方法才能返回 MPI::COMM_WORLD?当我尝试编译上述内容时,出现以下错误:

invalid abstract return type for member function 'MPI::Comm Parallel ::getCommunicator()

最佳答案

Zulan 是对的,C++ 绑定(bind)已从 MPI 3 中删除,因此确实不应该使用它们编写新代码。

它们被删除的原因是它们没有经过深思熟虑或维护,而且它们绝对不是很惯用,所以如果你使用它们,你会遇到很多奇怪的情况。 Boost::MPI好多了,但不幸的是只涵盖 MPI 1。

如果为了维护现有代码,您必须拥有此代码,则问题如下所述 here - 至少在 OpenMPI 中,MPI::Comm 被定义为纯虚拟类,因此您无法返回该类型的对象,因为无法创建该类型的对象;您只能返回一个子类型。 (我认为这是通过这种方式完成的,因此您可以将内部和内部通信器作为子类型)。

处理这种情况的经典方法是返回对象的引用,而不是对象本身,并让编译器处理向上转换:

#include <mpi.h>
#include <iostream>

class Parallel{      
    public:
        MPI::Comm &getCommunicator(){
            return MPI::COMM_WORLD;
        }
    protected:
        int iproc;
};

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

    Parallel* parallel;
    MPI::Init(argc, argv);
    int my_rank, size;

    my_rank = parallel->getCommunicator().Get_rank();
    size = parallel->getCommunicator().Get_size();
    std::cout << my_rank << "/" << size << std::endl;
    MPI::Finalize();
    return 0;
}

给予

$ mpic++ -o foo foo.cpp
$ mpiexec -np 4 ./foo
1/4
2/4
3/4
0/4

关于c++ - 无法编译返回 MPI::Comm 类型对象的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38392832/

相关文章:

c++ - 为什么我会使用 2 的补码来比较两个 double 而不是将它们的差异与 epsilon 值进行比较?

c++ - 如何使用mpirun为不同的程序使用不同的CPU内核?

c++ - MPI_Scatter 会减慢代码速度吗?

c - MPI 检查通信器是否为 MPI_COMM_WORLD

c++ - 如何从文件写入字符串

c++ - vector 范围为n1 n2的元素之和

Python 调用使用 MPI 的 (fortran) 库

c - 从一个通信器到另一个的 mpi 集体操作

c++ - 未声明的标识符,超出范围? (使用 C++ 列表)