Skip to content

Commit 9b451fb

Browse files
gh-137093: Fix race condition in test_embed.test_bpo20891 (GH-137094)
Use a `PyEvent` instead of a lock to fix a race on the free-threaded build.
1 parent fece15d commit 9b451fb

File tree

1 file changed

+6
-18
lines changed

1 file changed

+6
-18
lines changed

Programs/_testembed.c

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -379,9 +379,9 @@ static int test_pre_initialization_sys_options(void)
379379

380380

381381
/* bpo-20891: Avoid race condition when initialising the GIL */
382-
static void bpo20891_thread(void *lockp)
382+
static void bpo20891_thread(void *eventp)
383383
{
384-
PyThread_type_lock lock = *((PyThread_type_lock*)lockp);
384+
PyEvent *event = (PyEvent *)eventp;
385385

386386
PyGILState_STATE state = PyGILState_Ensure();
387387
if (!PyGILState_Check()) {
@@ -390,8 +390,7 @@ static void bpo20891_thread(void *lockp)
390390
}
391391

392392
PyGILState_Release(state);
393-
394-
PyThread_release_lock(lock);
393+
_PyEvent_Notify(event);
395394
}
396395

397396
static int test_bpo20891(void)
@@ -401,27 +400,16 @@ static int test_bpo20891(void)
401400

402401
/* bpo-20891: Calling PyGILState_Ensure in a non-Python thread must not
403402
crash. */
404-
PyThread_type_lock lock = PyThread_allocate_lock();
405-
if (!lock) {
406-
error("PyThread_allocate_lock failed!");
407-
return 1;
408-
}
409-
403+
PyEvent event = {0};
410404
_testembed_initialize();
411405

412-
unsigned long thrd = PyThread_start_new_thread(bpo20891_thread, &lock);
406+
unsigned long thrd = PyThread_start_new_thread(bpo20891_thread, &event);
413407
if (thrd == PYTHREAD_INVALID_THREAD_ID) {
414408
error("PyThread_start_new_thread failed!");
415409
return 1;
416410
}
417-
PyThread_acquire_lock(lock, WAIT_LOCK);
418411

419-
Py_BEGIN_ALLOW_THREADS
420-
/* wait until the thread exit */
421-
PyThread_acquire_lock(lock, WAIT_LOCK);
422-
Py_END_ALLOW_THREADS
423-
424-
PyThread_free_lock(lock);
412+
PyEvent_Wait(&event);
425413

426414
Py_Finalize();
427415

0 commit comments

Comments
 (0)