Skip to content

Commit 684cd0e

Browse files
committed
Issue #17522: Add the PyGILState_Check() API.
1 parent d4296fc commit 684cd0e

File tree

4 files changed

+28
-0
lines changed

4 files changed

+28
-0
lines changed

Doc/c-api/init.rst

+12
Original file line numberDiff line numberDiff line change
@@ -654,6 +654,18 @@ with sub-interpreters:
654654
made on the main thread. This is mainly a helper/diagnostic function.
655655
656656
657+
.. c:function:: int PyGILState_Check()
658+
659+
Return 1 if the current thread is holding the GIL and 0 otherwise.
660+
This function can be called from any thread at any time.
661+
Only if it has had its Python thread state initialized and currently is
662+
holding the GIL will it return 1.
663+
This is mainly a helper/diagnostic function. It can be useful
664+
for example in callback contexts or memory allocation functions when
665+
knowing that the GIL is locked can allow the caller to perform sensitive
666+
actions or otherwise behave differently.
667+
668+
657669
The following macros are normally used without a trailing semicolon; look for
658670
example usage in the Python source distribution.
659671

Include/pystate.h

+5
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,11 @@ PyAPI_FUNC(void) PyGILState_Release(PyGILState_STATE);
212212
*/
213213
PyAPI_FUNC(PyThreadState *) PyGILState_GetThisThreadState(void);
214214

215+
/* Helper/diagnostic function - return 1 if the current thread
216+
* currently holds the GIL, 0 otherwise
217+
*/
218+
PyAPI_FUNC(int) PyGILState_Check(void);
219+
215220
#endif /* #ifdef WITH_THREAD */
216221

217222
/* The implementation of sys._current_frames() Returns a dict mapping

Misc/NEWS

+2
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ What's New in Python 3.4.0 Alpha 1?
1010
Core and Builtins
1111
-----------------
1212

13+
- Issue #17522: Add the PyGILState_Check() API.
14+
1315
- Issue #16475: Support object instancing, recursion and interned strings
1416
in marshal
1517

Python/pystate.c

+9
Original file line numberDiff line numberDiff line change
@@ -697,6 +697,15 @@ PyGILState_GetThisThreadState(void)
697697
return (PyThreadState *)PyThread_get_key_value(autoTLSkey);
698698
}
699699

700+
int
701+
PyGILState_Check(void)
702+
{
703+
/* can't use PyThreadState_Get() since it will assert that it has the GIL */
704+
PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed(
705+
&_PyThreadState_Current);
706+
return tstate && (tstate == PyGILState_GetThisThreadState());
707+
}
708+
700709
PyGILState_STATE
701710
PyGILState_Ensure(void)
702711
{

0 commit comments

Comments
 (0)