Skip to content

Commit 395c048

Browse files
committed
Add compile option to select GIL implementation (Ref T11804)
See pybind#1276 for the rationale.
1 parent aabb3a4 commit 395c048

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

CMakeLists.txt

+4-1
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ endif()
2727

2828
option(PYBIND11_INSTALL "Install pybind11 header files?" ${PYBIND11_MASTER_PROJECT})
2929
option(PYBIND11_TEST "Build pybind11 test suite?" ${PYBIND11_MASTER_PROJECT})
30+
option(PYBIND11_USE_PYGILSTATE_API "Use PyGILState API for gil management?" OFF)
3031

3132
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/tools")
3233

@@ -101,7 +102,9 @@ if(NOT (CMAKE_VERSION VERSION_LESS 3.0)) # CMake >= 3.0
101102
$<BUILD_INTERFACE:${PYTHON_INCLUDE_DIRS}>
102103
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>)
103104
target_compile_options(pybind11 INTERFACE $<BUILD_INTERFACE:${PYBIND11_CPP_STANDARD}>)
104-
105+
if( PYBIND11_USE_PYGILSTATE_API )
106+
target_compile_definitions(pybind11 INTERFACE PYBIND11_USE_PYGILSTATE_API)
107+
endif()
105108
add_library(module INTERFACE)
106109
add_library(pybind11::module ALIAS module)
107110
if(NOT MSVC)

include/pybind11/pybind11.h

+18-2
Original file line numberDiff line numberDiff line change
@@ -1866,8 +1866,22 @@ void print(Args &&...args) {
18661866
detail::print(c.args(), c.kwargs());
18671867
}
18681868

1869-
#if defined(WITH_THREAD) && !defined(PYPY_VERSION)
1869+
#if defined(PYPY_VERSION)
1870+
class gil_scoped_acquire {
1871+
PyGILState_STATE state;
1872+
public:
1873+
gil_scoped_acquire() { state = PyGILState_Ensure(); }
1874+
~gil_scoped_acquire() { PyGILState_Release(state); }
1875+
};
18701876

1877+
class gil_scoped_release {
1878+
PyThreadState *state;
1879+
public:
1880+
gil_scoped_release() { state = PyEval_SaveThread(); }
1881+
~gil_scoped_release() { PyEval_RestoreThread(state); }
1882+
};
1883+
#else
1884+
#if defined(WITH_THREAD) && !defined(PYBIND11_USE_PYGILSTATE_API)
18711885
/* The functions below essentially reproduce the PyGILState_* API using a RAII
18721886
* pattern, but there are a few important differences:
18731887
*
@@ -1992,7 +2006,7 @@ class gil_scoped_release {
19922006
PyThreadState *tstate;
19932007
bool disassoc;
19942008
};
1995-
#elif defined(PYPY_VERSION)
2009+
#elif defined(PYBIND11_USE_PYGILSTATE_API)
19962010
class gil_scoped_acquire {
19972011
PyGILState_STATE state;
19982012
public:
@@ -2011,6 +2025,8 @@ class gil_scoped_acquire { };
20112025
class gil_scoped_release { };
20122026
#endif
20132027

2028+
#endif
2029+
20142030
error_already_set::~error_already_set() {
20152031
if (m_type) {
20162032
gil_scoped_acquire gil;

0 commit comments

Comments
 (0)