kodi
pythreadstate.h
1 /*
2  * Copyright (C) 2005-2018 Team Kodi
3  * This file is part of Kodi - https://kodi.tv
4  *
5  * SPDX-License-Identifier: GPL-2.0-or-later
6  * See LICENSES/README.md for more information.
7  */
8 
9 #pragma once
10 
11 
12 //WARNING: since this will unlock/lock the python global interpreter lock,
13 // it will not work recursively
14 
15 //this is basically a scoped version of a Py_BEGIN_ALLOW_THREADS .. Py_END_ALLOW_THREADS block
17 {
18  public:
19  explicit CPyThreadState(bool save = true)
20  {
21  m_threadState = NULL;
22 
23  if (save)
24  Save();
25  }
26 
28  {
29  Restore();
30  }
31 
32  void Save()
33  {
34  if (!m_threadState)
35  m_threadState = PyEval_SaveThread(); //same as Py_BEGIN_ALLOW_THREADS
36  }
37 
38  void Restore()
39  {
40  if (m_threadState)
41  {
42  PyEval_RestoreThread(m_threadState); //same as Py_END_ALLOW_THREADS
43  m_threadState = NULL;
44  }
45  }
46 
47  private:
48  PyThreadState* m_threadState;
49 };
50 
55 class GilSafeSingleLock : public CPyThreadState, public std::unique_lock<CCriticalSection>
56 {
57 public:
58  explicit GilSafeSingleLock(CCriticalSection& critSec)
59  : CPyThreadState(true), std::unique_lock<CCriticalSection>(critSec)
60  {
61  CPyThreadState::Restore();
62  }
63 };
64 
Definition: pythreadstate.h:16
A std::unique_lock<CCriticalSection> that will relinquish the GIL during the time it takes to obtain ...
Definition: pythreadstate.h:55