Debian Codegraph @

src/python/PyImath/PyImathUtil.cpp

raw
1 //
2 // SPDX-License-Identifier: BSD-3-Clause
3 // Copyright Contributors to the OpenEXR Project.
4 //
5
6 // clang-format off
7
8 #define BOOST_BIND_GLOBAL_PLACEHOLDERS
9 #include <boost/python.hpp>
10 #include <pystate.h>
11 #include "PyImathUtil.h"
12
13 namespace PyImath {
14
15 PyAcquireLock::PyAcquireLock()
16 {
17 _gstate = PyGILState_Ensure();
18 }
19
20 PyAcquireLock::~PyAcquireLock()
21 {
22 PyGILState_Release(_gstate);
23 }
24
25 #ifdef PLATFORM_LINUX
26 // On Windows, this extern is not needed and produces a symbol mismatch at link time.
27 // We should verify that it's still needed on Linux for Python 2.6.
28 extern "C" PyThreadState *_PyThreadState_Current;
29 #endif
30
31 static bool
32 pyHaveLock()
33 {
34 #if PY_MAJOR_VERSION > 2
35 return PyGILState_Check() != 0;
36 #else
37 // This is very much dependent on the current Python
38 // implementation of this functionality. If we switch versions of
39 // Python and the implementation changes, we'll have to change
40 // this code as well and introduce a #define for the Python
41 // version.
42
43 if (!Py_IsInitialized())
44 throw std::invalid_argument ("PyReleaseLock called without the interpreter initialized");
45
46 PyThreadState *myThreadState = PyGILState_GetThisThreadState();
47
48 // If the interpreter is initialized the gil is held if the
49 // current thread's thread state is the current thread state
50 return myThreadState != 0 && myThreadState == _PyThreadState_Current;
51 #endif
52 }
53
54 PyReleaseLock::PyReleaseLock()
55 {
56 // only call PyEval_SaveThread if we have the interpreter lock held,
57 // otherwise PyReleaseLock is a no-op.
58 if (pyHaveLock())
59 _save = PyEval_SaveThread();
60 else
61 _save = 0;
62 }
63
64 PyReleaseLock::~PyReleaseLock()
65 {
66 if (_save != 0)
67 PyEval_RestoreThread(_save);
68 }
69
70 } // namespace PyImath