来自字典析构函数的隔离错误

Segfault from dict destructor

本文关键字:隔离 错误 析构函数 字典      更新时间:2023-10-16

我对boost python,基本对象析构函数有问题。当对象boost::p ython::d ict在py_init范围内创建和销毁时,一切都很好。但是py_smth范围内,dict 只是在构造函数执行之后才创建成功,当本地 dict descructor 是打电话然后我有分段错误。

    class py_init
    {
    public:
        py_init::py_init()
        {
              Py_Initialize();
              object main_module = import("__main__");
              main_namespace = main_module.attr("__dict__");
              main_namespace["sys"] = import("sys');
              exec("sys.path.insert(0, "/foo/boo"), main_namespace, main_namespace);
        }
    object main_namespace;
    };

    class py_smth
    {
    public:
       py_smth(std::shared_ptr<py_init> py)
       {
             dict local;
       }
};
Backtrace:
Program terminated with signal SIGSEGV, Segmentation fault
#0  0x00007f501ddf9a38 in ?? () from /usr/lib/x86_64-linux-gnu/libpython3.4m.so.1.0
(gdb) bt
#0  0x00002b9545827a38 in ?? () from /usr/lib/x86_64-linux-gnu/libpython3.4m.so.1.0
#1  0x00002b95450ff12f in boost::python::api::object_base::~object_base() () from libplugin.so
#2  0x00002b95450ff060 in boost::python::api::object::~object() () from libplugin.so
#3  0x00002b9545101198 in boost::python::detail::dict_base::~dict_base() libplugin.so
#4  0x00002b9545101230 in boost::python::dict::~dict() libplugin.so

库版本:-增强版 1.54-蟒蛇 3.4.2

我不知道为什么...

好的,这是不起作用的示例代码

主.cpp文件:

#include <iostream>
#include <boost/python.hpp>
#include <memory>
#include "smth.h"
using namespace boost::python;
class py_init
{
public:
    py_init()
    {
             Py_Initialize();
             object main_module = import("__main__");
             main_namespace = main_module.attr("__dict__");
             main_namespace["sys"] = import("sys");
         main_namespace["time"] = import("time");
         main_namespace["threading"] = import("threading");
             exec("sys.path.insert(0, "/foo/boo")", main_namespace, main_namespace);
         exec("def foo():print ("bla"); time.sleep(1);" , main_namespace, main_namespace);
         exec("thread = threading.Thread(target=foo)" , main_namespace, main_namespace);
         exec("thread.start()" , main_namespace, main_namespace);
         state = PyEval_SaveThread();
    }
    ~py_init()
    {
          PyEval_RestoreThread(state);
          PyGILState_STATE gstate;
          gstate = PyGILState_Ensure();
          exec("thread.join()" , main_namespace, main_namespace);
          PyGILState_Release(gstate);
         std::cout<<"Py_init dest"<<std::endl;
    }
    object main_namespace;
    PyThreadState* state;
};
int main()
{
    std::shared_ptr<py_init> py(new py_init());
    smth s(py);
    s.print_foo();
    return 0;
}

#ifndef SMTH_H_
#define SMTH_H_
#include <boost/python.hpp>
#include <memory>
using namespace boost::python;
class py_init;
class smth
{
public:
    smth(std::shared_ptr<py_init> py)
    {
        dict local;
    }
    void print_foo()
    {
        std::cout<<"FOO"<<std::endl;
    }
    ~smth()
    {
        std::cout<<"smth dest"<<std::endl;
    }
};
#endif 

回溯:

> Program terminated with signal SIGSEGV, Segmentation fault.
> #0  0x00007f9c5d787a38 in ?? () from /usr/lib/x86_64-linux-gnu/libpython3.4m.so.1.0 (gdb) bt
> #0  0x00007f9c5d787a38 in ?? () from /usr/lib/x86_64-linux-gnu/libpython3.4m.so.1.0
> #1  0x0000000000401a9d in boost::python::api::object_base::~object_base() ()
> #2  0x0000000000401922 in boost::python::api::object::~object() ()
> #3  0x0000000000401b50 in boost::python::detail::dict_base::~dict_base() ()
> #4  0x0000000000401bde in boost::python::dict::~dict() ()
> #5  0x0000000000401c08 in smth::smth(std::shared_ptr<py_init>) ()
> #6  0x0000000000401727 in main ()

汇编:

g++ -std=c++0x -fPIC -I/usr/include/python3.4m -c main.cpp -o app.o g++ -std=c++0x app.o -lboost_python3 -lpython3.4m

程序正在调用未定义的行为,因为boost::python::dict对象是由不持有全局解释器锁 (GIL) 的线程创建和销毁的。 如果线程正在执行任何影响 python 托管对象的引用计数的操作,则需要获取 GIL。 若要解决此问题,请在 smth 构造函数中获取并释放 GIL。

smth::smth(std::shared_ptr<py_init> py)
{
  PyGILState_STATE gstate;
  gstate = PyGILState_Ensure(); // Acquire GIL.
  // Use scope to force destruction while GIL is held.
  {
    boost::python::dict local;
  } 
  PyGILState_Release(gstate); // Release GIL.
}

可能值得考虑使用 RAII 类来帮助管理 GIL。 例如,对于以下gil_lock类,当创建gil_lock对象时,调用线程将获取 GIL。 当gil_lock对象被析构时,它会释放 GIL。

/// @brief RAII class used to lock and unlock the GIL.
class gil_lock
{
public:
  gil_lock()  { state_ = PyGILState_Ensure(); }
  ~gil_lock() { PyGILState_Release(state_);   }
private:
  PyGILState_STATE state_;
};

然后,smth构造函数可以编写为:

smth::smth(std::shared_ptr<py_init> py)
{
  gil_lock lock;
  boost::python::dict local;
}

这是最小原始代码的注释版本。 它强调一旦py_init的构造函数返回,调用方就不会持有 GIL。 因此,boost::python::dict的创建和破坏都会导致未定义的行为。

class py_init
{
public:
  py_init()
  {
    Py_Initialize(); // Acquires GIL (1).
    // ... spawn Python thread that will compete for GIL.
    state = PyEval_SaveThread(); // Release GIL (0).
  }
  ~py_init()
  {
    PyEval_RestoreThread(state); // Acquire GIL (1). 
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure(); // Acquire GIL (2).
    // ...
    PyGILState_Release(gstate); // Release GIL (1).
  }
  PyThreadState* state;
};    
int main()
{
  std::shared_ptr<py_init> py(new py_init());
  // GIL not held.
  {
    // Modifying object without GIL; other thread may hold it.
    boost::python::dict local;
  }
} // ~py_init() acquires GIL.

在 Python 3.4 中,还可以使用 PyGILState_Check() 函数来检查调用线程是否持有 GIL。 根据文档,它主要是一个帮助程序/诊断功能。 对于早期版本,可以通过直接访问其中一个 Python 全局变量来执行类似的检查:

_PyThreadState_Current == PyGILState_GetThisThreadState();

PyThreadState_Get()函数不能用于这种类型的诊断,因为如果没有线程持有 GIL(这是一种有效状态),则会发出致命错误。