From a92ef139b10538877b978f340b8de0544980a324 Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Thu, 17 Sep 2026 16:34:50 +0200 Subject: [PATCH] gh-157415: Fix data race in pthread wrapper (#157430) Use free() instead of PyMem_RawFree() in pythread_wrapper() to avoid a data race if another thread calls PyMem_SetAllocator() in parallel. Reenable @nomemtest tests on TSAN. Co-authored-by: Nathan Goldbaum (cherry picked from commit d1878ccb44999bfa30f5a0e84b4383e6068e5b72) --- Python/thread_pthread.h | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Python/thread_pthread.h b/Python/thread_pthread.h index 8e7b9589615b124..e3a69789dec9e7f 100644 --- a/Python/thread_pthread.h +++ b/Python/thread_pthread.h @@ -237,7 +237,7 @@ pythread_wrapper(void *arg) pythread_callback *callback = arg; void (*func)(void *) = callback->func; void *func_arg = callback->arg; - PyMem_RawFree(arg); + free(callback); func(func_arg); return NULL; @@ -277,7 +277,9 @@ do_start_joinable_thread(void (*func)(void *), void *arg, pthread_t* out_id) pthread_attr_setscope(&attrs, PTHREAD_SCOPE_SYSTEM); #endif - pythread_callback *callback = PyMem_RawMalloc(sizeof(pythread_callback)); + // Use free() instead of PyMem_RawFree() in pythread_wrapper() to avoid a + // data race if another thread calls PyMem_SetAllocator() in parallel. + pythread_callback *callback = malloc(sizeof(pythread_callback)); if (callback == NULL) { return -1; @@ -299,7 +301,7 @@ do_start_joinable_thread(void (*func)(void *), void *arg, pthread_t* out_id) #endif if (status != 0) { - PyMem_RawFree(callback); + free(callback); return -1; } *out_id = th;