gpt4 book ai didi

python - 将 python 嵌入我的应用程序时内存泄漏

转载 作者:搜寻专家 更新时间:2023-10-31 00:29:04 24 4
gpt4 key购买 nike

当链接到 python 2.7.13 并在 Windows 10 上缓慢但稳定地运行时,以下程序会泄漏内存。

#include <Python.h>
#include <iostream>

int main()
{
std::cout << "Python version: " << PY_VERSION << std::endl;

while (true)
{
Py_Initialize();
//PyGC_Collect();
Py_Finalize();
}

return 0;
}

有趣的是,似乎并不是每次迭代都会泄漏内存。不过,我看到的是,无论泄漏如何,python 打印的引用计数每次迭代都会缓慢增加大约 90 个(非常量)计数。使用 Visual Studio 诊断工具,我发现泄漏来自于调用 PyImport_ImportModule(),当它从磁盘读取编译模块时(实际调用堆栈有几层深)。

是否需要任何我不知道的额外清理步骤?还是 Python 垃圾收集器有什么东西可能会导致这种情况,而这不是“真正的”内存泄漏?

最佳答案

Py_Finalize — Python/C API Reference Manual (强调我的):

<...>
Bugs and caveats: The destruction of modules and objects in modules is done in random order; this may cause destructors (__del__() methods) to fail when they depend on other objects (even functions) or modules. Dynamically loaded extension modules loaded by Python are not unloaded. Small amounts of memory allocated by the Python interpreter may not be freed (if you find a leak, please report it). Memory tied up in circular references between objects is not freed. Some memory allocated by extension modules may not be freed. Some extensions may not work properly if their initialization routine is called more than once; this can happen if an application calls Py_Initialize() and Py_Finalize() more than once.

关于python - 将 python 嵌入我的应用程序时内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42971734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com