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 b3b9ade4a3)
This commit is contained in:
Stefan Krah 2020-03-03 09:18:55 +01:00 committed by GitHub
parent 1827fc30f4
commit 5a92f42d87
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 7 additions and 2 deletions

View File

@ -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).

View File

@ -606,13 +606,12 @@ new_threadstate(PyInterpreterState *interp, int init)
tstate->context = NULL; tstate->context = NULL;
tstate->context_ver = 1; tstate->context_ver = 1;
tstate->id = ++interp->tstate_next_unique_id;
if (init) { if (init) {
_PyThreadState_Init(runtime, tstate); _PyThreadState_Init(runtime, tstate);
} }
HEAD_LOCK(runtime); HEAD_LOCK(runtime);
tstate->id = ++interp->tstate_next_unique_id;
tstate->prev = NULL; tstate->prev = NULL;
tstate->next = interp->tstate_head; tstate->next = interp->tstate_head;
if (tstate->next) if (tstate->next)