From 1a0c9ff1b1ca7b802d63830b65e9237ba7a33a84 Mon Sep 17 00:00:00 2001 From: "Gustavo J. A. M. Carneiro" Date: Tue, 5 Aug 2008 18:35:35 +0100 Subject: [PATCH] Make the generated reverse wrappers (virtual methods) python thread safe, i.e. they now acquire / release the Python GIL when called from C/C++ code, but only if Python threading was initialized (PyEval_ThreadsInitialized). --- pybindgen/typehandlers/base.py | 10 ++++++++++ pybindgen/utils.py | 2 ++ 2 files changed, 12 insertions(+) diff --git a/pybindgen/typehandlers/base.py b/pybindgen/typehandlers/base.py index fc1e6e4..6a4cc64 100644 --- a/pybindgen/typehandlers/base.py +++ b/pybindgen/typehandlers/base.py @@ -585,6 +585,16 @@ class ReverseWrapperBase(object): assert isinstance(decl_modifiers, (list, tuple)) assert all([isinstance(mod, str) for mod in decl_modifiers]) + + ## reverse wrappers are called from C/C++ code, when the Python GIL may not be held... + gil_state_var = self.declarations.declare_variable('PyGILState_STATE', '__py_gil_state') + self.before_call.write_code('%s = (PyEval_ThreadsInitialized() ? PyGILState_Ensure() : (PyGILState_STATE) 0);' + % gil_state_var) + self.before_call.add_cleanup_code('if (PyEval_ThreadsInitialized())\n' + ' PyGILState_Release(%s);' % gil_state_var) + + + self.declarations.declare_variable('PyObject*', 'py_retval') if self.return_value.ctype != 'void' \ and not self.return_value.REQUIRES_ASSIGNMENT_CONSTRUCTOR: diff --git a/pybindgen/utils.py b/pybindgen/utils.py index 33c6e0e..997278c 100644 --- a/pybindgen/utils.py +++ b/pybindgen/utils.py @@ -40,6 +40,8 @@ def write_preamble(code_sink, min_python_version=None): code_sink.writeln(r''' #if PY_VERSION_HEX < 0x02040000 +#define PyEval_ThreadsInitialized() 1 + #define Py_CLEAR(op) \ do { \ if (op) { \