pybind11内存泄漏和崩溃

2024-10-01 17:32:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我在pybind11中面临内存泄漏和崩溃问题

< P>我从Python文件“MyDL.Py”调用Python函数“MyFunc”,它使用Tensorflow Keras深度学习函数、NUMPY和ReISIS模块,使用PybDun11在重复性C++代码中。代码结构如下所示

class myclass {
  public:
   myclass() {
     py::initialize_interpreter();

     {
        py::module sys = py::module::import("sys");
        py::module os = py::module::import("os");
        py::str cwd = os.attr("getcwd")();
        py::print("os.cwd: ", cwd);
        py::str bin = cwd + py::str("/../bin");

        // Add bin to sys.path
        py::module site = py::module::import("site");
        site.attr("addsitedir")(bin);
      }
   }
   
   ~myclass() {
      py::finalize_interpreter();
   }

   int callpyfunc(string a1, string a2) {
     int retval;
     {
        py::module mydl = py::module::import("mydl");
        py::object result = mydl.attr("myfunc")(a1, a2);
        retval = result.cast<int>();
     }

    return retval;
   }
}

myclass *mcobj1;

int main() {

  mcobj1 = new myclass();
  int retval;

  while (/* some deep learning condition is not met */) {
     retval = mcobj1->callpyfunc(a1, a2);
  }

  del mcobj1;

}

该程序的内存大小持续增加,直至消耗整个62 GB RAM并崩溃。Python解释器似乎没有在每次调用“mydl.py”的“myfunc”时释放分配给不同对象的内存,即使在调用完成之后也是如此

以下是我在没有解决问题的情况下所做的一切:

  1. callpyfunc内使用作用域解释器,而不是执行initialize_interpreterfinalize_interpreter。但是在这种情况下,代码在第二次调用“callpyfunc”时安静地崩溃,第一次调用正常。这正是所提到的here

  2. 移动initialize_interpreter并在callpyfunc内导入诸如“sys”、“os”和finalize_interpreter等模块。但是在这种情况下,代码在第py::module mydl = py::module::import("mydl");行对“callpyfunc”的第二次调用中崩溃,并且永远无法完成解释器


Tags: 代码pyimportbinossysmyclassint

热门问题