summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Misc/NEWS.d/next/Core and Builtins/2020-03-02-20-12-33.bpo-39776.fNaxi_.rst6
-rw-r--r--Python/pystate.c3
2 files changed, 7 insertions, 2 deletions
diff --git a/Misc/NEWS.d/next/Core and Builtins/2020-03-02-20-12-33.bpo-39776.fNaxi_.rst b/Misc/NEWS.d/next/Core and Builtins/2020-03-02-20-12-33.bpo-39776.fNaxi_.rst
new file mode 100644
index 0000000..e5a00bd
--- /dev/null
+++ b/Misc/NEWS.d/next/Core and Builtins/2020-03-02-20-12-33.bpo-39776.fNaxi_.rst
@@ -0,0 +1,6 @@
+Fix race condition where threads created by PyGILState_Ensure() could get a
+duplicate id.
+
+This affects consumers of tstate->id like the contextvar caching machinery,
+which could return invalid cached objects under heavy thread load (observed
+in embedded scenarios).
diff --git a/Python/pystate.c b/Python/pystate.c
index ebc17ea..4001c63 100644
--- a/Python/pystate.c
+++ b/Python/pystate.c
@@ -606,13 +606,12 @@ new_threadstate(PyInterpreterState *interp, int init)
tstate->context = NULL;
tstate->context_ver = 1;
- tstate->id = ++interp->tstate_next_unique_id;
-
if (init) {
_PyThreadState_Init(tstate);
}
HEAD_LOCK(runtime);
+ tstate->id = ++interp->tstate_next_unique_id;
tstate->prev = NULL;
tstate->next = interp->tstate_head;
if (tstate->next)