@@ -499,42 +499,56 @@ PyEval_ThreadsInitialized(void)
499
499
return _PyEval_ThreadsInitialized ();
500
500
}
501
501
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
+
502
520
PyStatus
503
521
_PyEval_InitGIL (PyThreadState * tstate , int own_gil )
504
522
{
505
523
assert (tstate -> interp -> ceval .gil == NULL );
524
+ int locked ;
506
525
if (!own_gil ) {
507
526
PyInterpreterState * main_interp = _PyInterpreterState_Main ();
508
527
assert (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 );
514
530
}
515
-
516
531
/* 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 )) {
519
533
/* Currently, the GIL is shared by all interpreters,
520
534
and only the main interpreter is responsible to create
521
535
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 ) ;
524
538
// XXX For now we lie.
525
539
tstate -> 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 );
527
550
}
528
- assert (own_gil );
529
-
530
- assert (!gil_created (gil ));
531
551
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 );
538
552
return _PyStatus_OK ();
539
553
}
540
554
0 commit comments