[Python-checkins] cpython: Issue #17522: Add the PyGILState_Check() API.

kristjan.jonsson python-checkins at python.org
Sat Mar 23 11:48:37 CET 2013


http://hg.python.org/cpython/rev/2e92d1567ad7
changeset:   82889:2e92d1567ad7
parent:      82887:81083f8841fe
user:        Kristján Valur Jónsson <sweskman at gmail.com>
date:        Sat Mar 23 03:36:16 2013 -0700
summary:
  Issue #17522: Add the PyGILState_Check() API.

files:
  Doc/c-api/init.rst |  12 ++++++++++++
  Include/pystate.h  |   5 +++++
  Misc/NEWS          |   2 ++
  Python/pystate.c   |   9 +++++++++
  4 files changed, 28 insertions(+), 0 deletions(-)


diff --git a/Doc/c-api/init.rst b/Doc/c-api/init.rst
--- a/Doc/c-api/init.rst
+++ b/Doc/c-api/init.rst
@@ -654,6 +654,18 @@
    made on the main thread.  This is mainly a helper/diagnostic function.
 
 
+.. c:function:: int PyGILState_Check()
+
+   Return 1 if the current thread is holding the GIL and 0 otherwise.
+   This function can be called from any thread at any time.
+   Only if it has had its Python thread state initialized and currently is
+   holding the GIL will it return 1.
+   This is mainly a helper/diagnostic function.  It can be useful
+   for example in callback contexts or memory allocation functions when
+   knowing that the GIL is locked can allow the caller to perform sensitive
+   actions or otherwise behave differently.
+
+
 The following macros are normally used without a trailing semicolon; look for
 example usage in the Python source distribution.
 
diff --git a/Include/pystate.h b/Include/pystate.h
--- a/Include/pystate.h
+++ b/Include/pystate.h
@@ -212,6 +212,11 @@
 */
 PyAPI_FUNC(PyThreadState *) PyGILState_GetThisThreadState(void);
 
+/* Helper/diagnostic function - return 1 if the current thread
+ * currently holds the GIL, 0 otherwise
+ */
+PyAPI_FUNC(int) PyGILState_Check(void);
+
 #endif   /* #ifdef WITH_THREAD */
 
 /* The implementation of sys._current_frames()  Returns a dict mapping
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -10,6 +10,8 @@
 Core and Builtins
 -----------------
 
+- Issue #17522: Add the PyGILState_Check() API.
+
 - Issue #16475: Support object instancing, recursion and interned strings
   in marshal
 
diff --git a/Python/pystate.c b/Python/pystate.c
--- a/Python/pystate.c
+++ b/Python/pystate.c
@@ -697,6 +697,15 @@
     return (PyThreadState *)PyThread_get_key_value(autoTLSkey);
 }
 
+int
+PyGILState_Check(void)
+{
+    /* can't use PyThreadState_Get() since it will assert that it has the GIL */
+    PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed(
+        &_PyThreadState_Current);
+    return tstate && (tstate == PyGILState_GetThisThreadState());
+}
+
 PyGILState_STATE
 PyGILState_Ensure(void)
 {

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list