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