@@ -651,48 +651,56 @@ class internals_pp_manager {
651651 // / acquire the GIL. Will never return nullptr.
652652 std::unique_ptr<InternalsType> *get_pp () {
653653#ifdef PYBIND11_HAS_SUBINTERPRETER_SUPPORT
654- // Whenever the interpreter changes on the current thread we need to invalidate the
655- // internals_pp so that it can be pulled from the interpreter's state dict. That is
656- // slow, so we use the current PyThreadState to check if it is necessary.
657- auto *tstate = get_thread_state_unchecked ();
658- if (!tstate || tstate->interp != last_istate_tls ()) {
659- gil_scoped_acquire_simple gil;
660- if (!tstate) {
661- tstate = get_thread_state_unchecked ();
654+ if (get_num_interpreters_seen () > 1 ) {
655+ // Whenever the interpreter changes on the current thread we need to invalidate the
656+ // internals_pp so that it can be pulled from the interpreter's state dict. That is
657+ // slow, so we use the current PyThreadState to check if it is necessary.
658+ auto *tstate = get_thread_state_unchecked ();
659+ if (!tstate || tstate->interp != last_istate_tls ()) {
660+ gil_scoped_acquire_simple gil;
661+ if (!tstate) {
662+ tstate = get_thread_state_unchecked ();
663+ }
664+ last_istate_tls () = tstate->interp ;
665+ internals_p_tls () = get_or_create_pp_in_state_dict ();
662666 }
663- last_istate_tls () = tstate->interp ;
664- internals_p_tls () = get_or_create_pp_in_state_dict ();
667+ return internals_p_tls ();
665668 }
666- return internals_p_tls ();
667- #else
669+ #endif
668670 if (!internals_singleton_pp_) {
669671 gil_scoped_acquire_simple gil;
670672 internals_singleton_pp_ = get_or_create_pp_in_state_dict ();
671673 }
672674 return internals_singleton_pp_;
673- #endif
674675 }
675676
676677 // / Drop all the references we're currently holding.
677678 void unref () {
678679#ifdef PYBIND11_HAS_SUBINTERPRETER_SUPPORT
679- last_istate_tls () = nullptr ;
680- internals_p_tls () = nullptr ;
680+ if (get_num_interpreters_seen () > 1 ) {
681+ last_istate_tls () = nullptr ;
682+ internals_p_tls () = nullptr ;
683+ return ;
684+ }
681685#endif
682686 internals_singleton_pp_ = nullptr ;
683687 }
684688
685689 void destroy () {
686690#ifdef PYBIND11_HAS_SUBINTERPRETER_SUPPORT
687- auto *tstate = get_thread_state_unchecked ();
688- // this could be called without an active interpreter, just use what was cached
689- if (!tstate || tstate->interp == last_istate_tls ()) {
690- auto tpp = internals_p_tls ();
691- delete tpp;
691+ if (get_num_interpreters_seen () > 1 ) {
692+ auto *tstate = get_thread_state_unchecked ();
693+ // this could be called without an active interpreter, just use what was cached
694+ if (!tstate || tstate->interp == last_istate_tls ()) {
695+ auto tpp = internals_p_tls ();
696+
697+ delete tpp;
698+ }
699+ unref ();
700+ return ;
692701 }
693- #else
694- delete internals_singleton_pp_;
695702#endif
703+ delete internals_singleton_pp_;
696704 unref ();
697705 }
698706
0 commit comments