python - 在 boost.python 中包装 MPI

标签 python c++ boost mpi

我已经设法使用 Boost.python 编写包装器来初始化和完成 MPI 环境,但我不确定是否一切都已正确初始化。我还没有遇到任何问题,但我想看看我正在做的事情是否不正确并且会在以后引起问题,或者是否有更好的方法来做到这一点。

我知道 python 确实绑定(bind)了 MPI(通过 mpi4py),但这不能正确满足我的需求。下面的简单示例可以用 mpi4py 代替,但我实际上不需要初始化普通 MPI 环境:我需要初始化一个专门的 MPI 环境 (MADNESS/TiledArray),其中没有我可以找到的 python 绑定(bind)。

我的文件结构如下:

接口(interface).cxx:

#include <iostream>
#include <boost/python.hpp>
#include <mpi.h>

void initMPI(int argc, boost::python::list argv){
  char ** argv_ = new char *[argc];
  for(auto i = 0; i < argc; i++){
    std::string str = boost::python::extract<std::string>(argv[i]);
    auto len = str.length();
    argv_[i] = new char[len+1];
    strncpy(argv_[i],&str[0],len);
    argv_[i][len] = '\0'; // Termination character
  }
  MPI_Init(&argc,&argv_);
  for(auto i = 0; i < argc; i++){
    delete [] argv_[i];
  }
  delete [] argv_;
};

void finalizeMPI(){
  MPI_Finalize();
};

void hello(){
  int world_size, rank, name_len;
  std::string name;
  name.reserve(MPI_MAX_PROCESSOR_NAME);
  MPI_Comm_size(MPI_COMM_WORLD,&world_size);
  MPI_Comm_rank(MPI_COMM_WORLD,&rank);
  MPI_Get_processor_name(&name[0],&name_len);
printf("Hello world from processor %s, rank %d"
           " out of %d processors\n",
           name.c_str(), rank, world_size);
};

BOOST_PYTHON_MODULE(mpiinterface){
  boost::python::def("init", initMPI);
  boost::python::def("finalize", finalizeMPI);
  boost::python::def("hello",hello);
};

测试.py:

import sys,os
sys.path.append('/home/dbwy/devel/tests/MPI/boost.python')
import mpiinterface

mpiinterface.init(len(sys.argv),sys.argv)
mpiinterface.hello();
mpiinterface.finalize();

编译后,它确实给我正确的输出:

[dbwy@medusa boost.python]$ mpirun -np 4 python test.py
Hello world from processor medusa.chem.washington.edu, rank 0 out of 4 processors
Hello world from processor medusa.chem.washington.edu, rank 3 out of 4 processors
Hello world from processor medusa.chem.washington.edu, rank 1 out of 4 processors
Hello world from processor medusa.chem.washington.edu, rank 2 out of 4 processors

真的这么简单吗?还是我错过了一些以后会造成灾难性后果的大事?

最佳答案

由于现在几乎所有现有的 MPI 实现都符合 1998 年发布的 MPI-2 规范,因此根本不需要对参数列表进行整个处理。从 MPI-2 开始,可以通过调用 MPI_Init(NULL, NULL) 来初始化 MPI .

事实上,使用 MPI 就像调用 MPI_Init 一样简单一次在您的申请开始时和MPI_Finalize 一次 在它退出之前。如果你的程序是多线程的,那么你应该替换 MPI_Init MPI_Init_thread 并确保 MPI 库支持所需级别的多线程。

关于python - 在 boost.python 中包装 MPI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34141178/

相关文章:

c++ - Boost序列化数据标准

c++ - Xcode MongoDB Boost 导入 <angle>

c++ - 如何禁用 boost::wave 的部分概念检查?

python - 如何修复 "DeprecationWarning: DataFrames with non-bool types result in worse computationalperformance..."

python - 如果元素总和为给定数字,则追加到列表中

c++ - 使用 vector 中的值(特征)来计算 opencv 的余弦相似度

c++ - 头文件中的多重定义

python - "Lazy"Python中的列表项评估

python - sqlalchemy 通过比较 datetime.now() 和列默认日期进行过滤

c++ - 如何以最少的代码优化翻译枚举?