Skip to content

Commit 5a92f42

Browse files
author
Stefan Krah
authored
bpo-39776: Lock ++interp->tstate_next_unique_id. (GH-18746) (#18746) (#18752)
- Threads created by PyGILState_Ensure() could have a duplicate tstate->id. (cherry picked from commit b3b9ade)
1 parent 1827fc3 commit 5a92f42

File tree

2 files changed

+7
-2
lines changed

2 files changed

+7
-2
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 & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -606,13 +606,12 @@ new_threadstate(PyInterpreterState *interp, int init)
606606
tstate->context = NULL;
607607
tstate->context_ver = 1;
608608

609-
tstate->id = ++interp->tstate_next_unique_id;
610-
611609
if (init) {
612610
_PyThreadState_Init(runtime, tstate);
613611
}
614612

615613
HEAD_LOCK(runtime);
614+
tstate->id = ++interp->tstate_next_unique_id;
616615
tstate->prev = NULL;
617616
tstate->next = interp->tstate_head;
618617
if (tstate->next)

0 commit comments

Comments
 (0)