@@ -499,42 +499,56 @@ PyEval_ThreadsInitialized(void)
499499return _PyEval_ThreadsInitialized ();
500500}
501501
502+ static void
503+ init_shared_gil (PyInterpreterState * interp ,struct _gil_runtime_state * gil )
504+ {
505+ assert (gil_created (gil ));
506+ interp -> ceval .gil = gil ;
507+ interp -> ceval .own_gil = 0 ;
508+ }
509+
510+ static void
511+ init_own_gil (PyInterpreterState * interp ,struct _gil_runtime_state * gil )
512+ {
513+ assert (!gil_created (gil ));
514+ create_gil (gil );
515+ assert (gil_created (gil ));
516+ interp -> ceval .gil = gil ;
517+ interp -> ceval .own_gil = 1 ;
518+ }
519+
502520PyStatus
503521_PyEval_InitGIL (PyThreadState * tstate ,int own_gil )
504522{
505523assert (tstate -> interp -> ceval .gil == NULL );
524+ int locked ;
506525if (!own_gil ) {
507526PyInterpreterState * main_interp = _PyInterpreterState_Main ();
508527assert (tstate -> interp != main_interp );
509- struct _gil_runtime_state * gil = main_interp -> ceval .gil ;
510- assert (gil_created (gil ));
511- tstate -> interp -> ceval .gil = gil ;
512- tstate -> interp -> ceval .own_gil = 0 ;
513- return _PyStatus_OK ();
528+ init_shared_gil (tstate -> interp ,main_interp -> ceval .gil );
529+ locked = _Py_atomic_load_relaxed (& main_interp -> ceval .gil -> locked );
514530 }
515-
516531/* XXX per-interpreter GIL */
517- struct _gil_runtime_state * gil = & tstate -> interp -> runtime -> ceval .gil ;
518- if (!_Py_IsMainInterpreter (tstate -> interp )) {
532+ else if (!_Py_IsMainInterpreter (tstate -> interp )) {
519533/* Currently, the GIL is shared by all interpreters,
520534 and only the main interpreter is responsible to create
521535 and destroy it. */
522- assert ( gil_created ( gil )) ;
523- tstate -> interp -> ceval . gil = gil ;
536+ struct _gil_runtime_state * main_gil = _PyInterpreterState_Main () -> ceval . gil ;
537+ init_shared_gil ( tstate -> interp , main_gil ) ;
524538// XXX For now we lie.
525539tstate -> interp -> ceval .own_gil = 1 ;
526- return _PyStatus_OK ();
540+ locked = _Py_atomic_load_relaxed (& main_gil -> locked );
541+ }
542+ else {
543+ PyThread_init_thread ();
544+ // XXX per-interpreter GIL: switch to interp->ceval._gil.
545+ init_own_gil (tstate -> interp ,& tstate -> interp -> runtime -> ceval .gil );
546+ locked = 0 ;
547+ }
548+ if (!locked ) {
549+ take_gil (tstate );
527550 }
528- assert (own_gil );
529-
530- assert (!gil_created (gil ));
531551
532- PyThread_init_thread ();
533- create_gil (gil );
534- assert (gil_created (gil ));
535- tstate -> interp -> ceval .gil = gil ;
536- tstate -> interp -> ceval .own_gil = 1 ;
537- take_gil (tstate );
538552return _PyStatus_OK ();
539553}
540554