Skip to content

Commit 852aee6

Browse files
author
Stefan Krah
authored
bpo-39776: Lock ++interp->tstate_next_unique_id (GH-18746)
- Threads created by PyGILState_Ensure() could have a duplicate tstate->id. (cherry picked from commit b3b9ade)
1 parent 72fff60 commit 852aee6

File tree

2 files changed

+7
-1
lines changed

2 files changed

+7
-1
lines changed
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
Fix race condition where threads created by PyGILState_Ensure() could get a
2+
duplicate id.
3+
4+
This affects consumers of tstate->id like the contextvar caching machinery,
5+
which could return invalid cached objects under heavy thread load (observed
6+
in embedded scenarios).

Python/pystate.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -411,12 +411,12 @@ new_threadstate(PyInterpreterState *interp, int init)
411411
tstate->context = NULL;
412412
tstate->context_ver = 1;
413413

414-
tstate->id = ++interp->tstate_next_unique_id;
415414

416415
if (init)
417416
_PyThreadState_Init(tstate);
418417

419418
HEAD_LOCK();
419+
tstate->id = ++interp->tstate_next_unique_id;
420420
tstate->prev = NULL;
421421
tstate->next = interp->tstate_head;
422422
if (tstate->next)

0 commit comments

Comments
 (0)