All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
pyLock.h
1//
2// Copyright 2016 Pixar
3//
4// Licensed under the terms set forth in the LICENSE.txt file available at
5// https://openusd.org/license.
6//
7#ifndef PXR_BASE_TF_PY_LOCK_H
8#define PXR_BASE_TF_PY_LOCK_H
9
10#include "pxr/pxr.h"
11
12#ifdef PXR_PYTHON_SUPPORT_ENABLED
13
15
16#include "pxr/base/tf/api.h"
17
18PXR_NAMESPACE_OPEN_SCOPE
19
105class TfPyLock {
106public:
108 TF_API TfPyLock();
109
111 TF_API ~TfPyLock();
112
114 TF_API void Acquire();
115
117 TF_API void Release();
118
122 TF_API void BeginAllowThreads();
123
126 TF_API void EndAllowThreads();
127
128private:
129 // Non-acquiring constructor for TfPyEnsureGILUnlockedObj's use.
130 friend struct TfPyEnsureGILUnlockedObj;
131 enum _UnlockedTag { _ConstructUnlocked };
132 explicit TfPyLock(_UnlockedTag);
133
134 PyGILState_STATE _gilState;
135 PyThreadState *_savedState;
136 bool _acquired:1;
137 bool _allowingThreads:1;
138};
139
140// Helper class for TF_PY_ALLOW_THREADS_IN_SCOPE()
141struct TfPyEnsureGILUnlockedObj
142{
143 // Do nothing if the current thread does not have the GIL, otherwise unlock
144 // the GIL, and relock upon destruction.
145 TF_API TfPyEnsureGILUnlockedObj();
146private:
147 TfPyLock _lock;
148};
149
173#define TF_PY_ALLOW_THREADS_IN_SCOPE() \
174 TfPyEnsureGILUnlockedObj __py_lock_allow_threads__
175
176PXR_NAMESPACE_CLOSE_SCOPE
177
178#else
179
180// When python is disabled, we stub this macro out to nothing.
181#define TF_PY_ALLOW_THREADS_IN_SCOPE()
182
183#endif // PXR_PYTHON_SUPPORT_ENABLED
184
185#endif // PXR_BASE_TF_PY_LOCK_H
Convenience class for accessing the Python Global Interpreter Lock.
Definition: pyLock.h:105
TF_API ~TfPyLock()
Releases Python GIL and restores prior threads state.
TF_API void BeginAllowThreads()
Unlock the GIL temporarily to allow other threads to use python.
TF_API TfPyLock()
Acquires the Python GIL and swaps in callers thread state.
TF_API void EndAllowThreads()
End allowing other threads, reacquiring the lock state.
TF_API void Acquire()
(Re)acquires GIL and thread state, if previously released.
TF_API void Release()
Explicitly releases GIL and thread state.
Intended to replace a direct include of Python.h, which causes several build problems with certain co...