Create a new subinterpreter with the specified configuration @note This function acquires (and then releases) the main interpreter GIL, but the main interpreter and its GIL are not required to be held prior to calling this function.
| 68 | /// @note This function acquires (and then releases) the main interpreter GIL, but the main |
| 69 | /// interpreter and its GIL are not required to be held prior to calling this function. |
| 70 | static subinterpreter create(PyInterpreterConfig const &cfg) { |
| 71 | |
| 72 | error_scope err_scope; |
| 73 | subinterpreter result; |
| 74 | { |
| 75 | // we must hold the main GIL in order to create a subinterpreter |
| 76 | subinterpreter_scoped_activate main_guard(main()); |
| 77 | |
| 78 | auto *prev_tstate = PyThreadState_Get(); |
| 79 | |
| 80 | PyStatus status; |
| 81 | |
| 82 | { |
| 83 | /* |
| 84 | Several internal CPython modules are lacking proper subinterpreter support in 3.12 |
| 85 | even though it is "stable" in that version. This most commonly seems to cause |
| 86 | crashes when two interpreters concurrently initialize, which imports several things |
| 87 | (like builtins, unicode, codecs). |
| 88 | */ |
| 89 | #if PY_VERSION_HEX < 0x030D0000 && defined(Py_MOD_PER_INTERPRETER_GIL_SUPPORTED) |
| 90 | static std::mutex one_at_a_time; |
| 91 | std::lock_guard<std::mutex> guard(one_at_a_time); |
| 92 | #endif |
| 93 | status = Py_NewInterpreterFromConfig(&result.creation_tstate_, &cfg); |
| 94 | } |
| 95 | |
| 96 | // this doesn't raise a normal Python exception, it provides an exit() status code. |
| 97 | if (PyStatus_Exception(status) != 0) { |
| 98 | pybind11_fail("failed to create new sub-interpreter"); |
| 99 | } |
| 100 | |
| 101 | // upon success, the new interpreter is activated in this thread |
| 102 | result.istate_ = result.creation_tstate_->interp; |
| 103 | detail::has_seen_non_main_interpreter() = true; |
| 104 | detail::get_internals(); // initialize internals.tstate, amongst other things... |
| 105 | |
| 106 | // In 3.13+ this state should be deleted right away, and the memory will be reused for |
| 107 | // the next threadstate on this interpreter. However, on 3.12 we cannot do that, we |
| 108 | // must keep it around (but not use it) ... see destructor. |
| 109 | #if PY_VERSION_HEX >= 0x030D0000 |
| 110 | PyThreadState_Clear(result.creation_tstate_); |
| 111 | PyThreadState_DeleteCurrent(); |
| 112 | #endif |
| 113 | |
| 114 | // we have to switch back to main, and then the scopes will handle cleanup |
| 115 | PyThreadState_Swap(prev_tstate); |
| 116 | } |
| 117 | return result; |
| 118 | } |
| 119 | |
| 120 | /// Calls create() with a default configuration of an isolated interpreter that disallows fork, |
| 121 | /// exec, and Python threads. |