来自dict析构函数的Segfault

时间:2015-01-29 16:43:17

标签: python c++ boost dictionary destructor

我对boost python,基础对象析构函数有问题。 当在py_init范围内创建并销毁对象boost :: python :: dict时,一切都很好。 但是在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

Libs版本: - 升级版本1.54 -python 3.4.2

我不知道为什么......

确定。这是不起作用的示例代码

main.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;
}

smth.h

#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

1 个答案:

答案 0 :(得分:1)

程序正在调用未定义的行为,因为boost::python::dict对象是由一个不包含Global Interpreter Lock(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(这是一个有效状态),它会发出致命错误。