]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.14] gh-137093: Fix race condition in `test_embed.test_bpo20891` (GH-137094) (...
authorKumar Aditya <kumaraditya@python.org>
Fri, 24 Oct 2025 07:51:44 +0000 (13:21 +0530)
committerGitHub <noreply@github.com>
Fri, 24 Oct 2025 07:51:44 +0000 (13:21 +0530)
Use a `PyEvent` instead of a lock to fix a race on the free-threaded build.
(cherry picked from commit 9b451fb457a5de9ed535a0e2f41161dfaa9a419a)

Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
Programs/_testembed.c

index 41cc5b145344ae8fbb68eed1cba9da610bca316c..6958a1679a2a0cd71778a6e6048d43f2aff6c1ff 100644 (file)
@@ -413,9 +413,9 @@ static int test_pre_initialization_sys_options(void)
 
 
 /* bpo-20891: Avoid race condition when initialising the GIL */
-static void bpo20891_thread(void *lockp)
+static void bpo20891_thread(void *eventp)
 {
-    PyThread_type_lock lock = *((PyThread_type_lock*)lockp);
+    PyEvent *event = (PyEvent *)eventp;
 
     PyGILState_STATE state = PyGILState_Ensure();
     if (!PyGILState_Check()) {
@@ -424,8 +424,7 @@ static void bpo20891_thread(void *lockp)
     }
 
     PyGILState_Release(state);
-
-    PyThread_release_lock(lock);
+    _PyEvent_Notify(event);
 }
 
 static int test_bpo20891(void)
@@ -435,27 +434,17 @@ static int test_bpo20891(void)
 
     /* bpo-20891: Calling PyGILState_Ensure in a non-Python thread must not
        crash. */
-    PyThread_type_lock lock = PyThread_allocate_lock();
-    if (!lock) {
-        error("PyThread_allocate_lock failed!");
-        return 1;
-    }
 
     _testembed_Py_InitializeFromConfig();
+    PyEvent event = {0};
 
-    unsigned long thrd = PyThread_start_new_thread(bpo20891_thread, &lock);
+    unsigned long thrd = PyThread_start_new_thread(bpo20891_thread, &event);
     if (thrd == PYTHREAD_INVALID_THREAD_ID) {
         error("PyThread_start_new_thread failed!");
         return 1;
     }
-    PyThread_acquire_lock(lock, WAIT_LOCK);
-
-    Py_BEGIN_ALLOW_THREADS
-    /* wait until the thread exit */
-    PyThread_acquire_lock(lock, WAIT_LOCK);
-    Py_END_ALLOW_THREADS
 
-    PyThread_free_lock(lock);
+    PyEvent_Wait(&event);
 
     Py_Finalize();