| 1 | // Copyright John Zwinck 2012.
|
|---|
| 2 | // Distributed under the Boost Software License, Version 1.0. (See
|
|---|
| 3 | // accompanying file LICENSE_1_0.txt or copy at
|
|---|
| 4 | // http://www.boost.org/LICENSE_1_0.txt)
|
|---|
| 5 | #include "gil.hpp"
|
|---|
| 6 |
|
|---|
| 7 | # include <boost/assert.hpp>
|
|---|
| 8 | # include <boost/thread/tss.hpp>
|
|---|
| 9 |
|
|---|
| 10 | namespace boost { namespace python {
|
|---|
| 11 |
|
|---|
| 12 | namespace {
|
|---|
| 13 |
|
|---|
| 14 | void thread_cleanup(PyThreadState*)
|
|---|
| 15 | {
|
|---|
| 16 | // nothing needs to be done here
|
|---|
| 17 | }
|
|---|
| 18 |
|
|---|
| 19 | boost::thread_specific_ptr<PyThreadState> g_thread_state(thread_cleanup);
|
|---|
| 20 |
|
|---|
| 21 | } // namespace
|
|---|
| 22 |
|
|---|
| 23 | gil_guard_release::gil_guard_release()
|
|---|
| 24 | : m_do_acquire(false)
|
|---|
| 25 | {
|
|---|
| 26 | if (!g_thread_state.get() && PyEval_ThreadsInitialized())
|
|---|
| 27 | {
|
|---|
| 28 | g_thread_state.reset(PyEval_SaveThread());
|
|---|
| 29 | m_do_acquire = true;
|
|---|
| 30 | }
|
|---|
| 31 | }
|
|---|
| 32 |
|
|---|
| 33 | gil_guard_release::~gil_guard_release()
|
|---|
| 34 | {
|
|---|
| 35 | if (m_do_acquire)
|
|---|
| 36 | {
|
|---|
| 37 | if (g_thread_state.get())
|
|---|
| 38 | {
|
|---|
| 39 | PyEval_RestoreThread(g_thread_state.get());
|
|---|
| 40 | g_thread_state.reset();
|
|---|
| 41 | }
|
|---|
| 42 | else
|
|---|
| 43 | {
|
|---|
| 44 | // This should never happen.
|
|---|
| 45 | BOOST_ASSERT(false);
|
|---|
| 46 | }
|
|---|
| 47 | }
|
|---|
| 48 | }
|
|---|
| 49 |
|
|---|
| 50 | gil_guard_acquire::gil_guard_acquire()
|
|---|
| 51 | : m_thread_state(g_thread_state.get())
|
|---|
| 52 | {
|
|---|
| 53 | if (m_thread_state)
|
|---|
| 54 | {
|
|---|
| 55 | PyEval_RestoreThread(m_thread_state);
|
|---|
| 56 | g_thread_state.reset();
|
|---|
| 57 | }
|
|---|
| 58 | }
|
|---|
| 59 |
|
|---|
| 60 | gil_guard_acquire::~gil_guard_acquire()
|
|---|
| 61 | {
|
|---|
| 62 | if (m_thread_state)
|
|---|
| 63 | {
|
|---|
| 64 | BOOST_ASSERT(!g_thread_state.get());
|
|---|
| 65 | g_thread_state.reset(PyEval_SaveThread());
|
|---|
| 66 | }
|
|---|
| 67 | }
|
|---|
| 68 |
|
|---|
| 69 | }} // namespace boost::python
|
|---|
| 70 |
|
|---|