@@ -810,7 +810,15 @@ new_threadstate(PyInterpreterState *interp)
810
810
{
811
811
PyThreadState * tstate ;
812
812
_PyRuntimeState * runtime = interp -> runtime ;
813
-
813
+ // We don't need to allocate a thread state for the main interpreter
814
+ // (the common case), but doing it later for the other case revealed a
815
+ // reentrancy problem (deadlock). So for now we always allocate before
816
+ // taking the interpreters lock. See GH-96071.
817
+ PyThreadState * new_tstate = alloc_threadstate ();
818
+ int used_newtstate ;
819
+ if (new_tstate == NULL ) {
820
+ return NULL ;
821
+ }
814
822
/* We serialize concurrent creation to protect global state. */
815
823
HEAD_LOCK (runtime );
816
824
@@ -822,18 +830,15 @@ new_threadstate(PyInterpreterState *interp)
822
830
if (old_head == NULL ) {
823
831
// It's the interpreter's initial thread state.
824
832
assert (id == 1 );
825
-
833
+ used_newtstate = 0 ;
826
834
tstate = & interp -> _initial_thread ;
827
835
}
828
836
else {
829
837
// Every valid interpreter must have at least one thread.
830
838
assert (id > 1 );
831
839
assert (old_head -> prev == NULL );
832
-
833
- tstate = alloc_threadstate ();
834
- if (tstate == NULL ) {
835
- goto error ;
836
- }
840
+ used_newtstate = 1 ;
841
+ tstate = new_tstate ;
837
842
// Set to _PyThreadState_INIT.
838
843
memcpy (tstate ,
839
844
& initial ._main_interpreter ._initial_thread ,
@@ -844,11 +849,11 @@ new_threadstate(PyInterpreterState *interp)
844
849
init_threadstate (tstate , interp , id , old_head );
845
850
846
851
HEAD_UNLOCK (runtime );
852
+ if (!used_newtstate ) {
853
+ // Must be called with lock unlocked to avoid re-entrancy deadlock.
854
+ PyMem_RawFree (new_tstate );
855
+ }
847
856
return tstate ;
848
-
849
- error :
850
- HEAD_UNLOCK (runtime );
851
- return NULL ;
852
857
}
853
858
854
859
PyThreadState *
0 commit comments