В версии 3.12 CPython API появилась функция
Py_NewInterpreterFromConfig принимающая параметр
PyInterpreterConfig с полем
.gil, которому можно присвоить значение
PyInterpreterConfig_OWN_GIL (Use the sub-interpreter’s own GIL).
Может уважаемые habr-овцы подскажут, можно ли теперь заставить работать несколько интерпретаторов CPython параллельно в одном процессе?
Такой код крешится при большом количестве потоков (Win10, MSVC):
#include <python.h>
#include <thread>
#include <vector>
namespace
{
void foo(void)
{
constexpr PyInterpreterConfig config =
{ .use_main_obmalloc = 0,
.check_multi_interp_extensions = 1,
.gil = PyInterpreterConfig_OWN_GIL,
};
PyThreadState *interpreter{};
Py_NewInterpreterFromConfig(&interpreter, &config);
PyRun_SimpleString("X = 'SUB'");
PyRun_SimpleString("print('X:', X)");
Py_EndInterpreter(interpreter);
}
}
int main()
{
Py_InitializeEx(1);
PyRun_SimpleString("X = 'MAIN'");
PyRun_SimpleString("print('Befor sub-interpreters X:', X)");
for(auto &&t: std::vector<std::jthread>(256))
t = std::jthread{ foo };
PyRun_SimpleString("print('After sub-interpreters X:', X)");
Py_FinalizeEx();
}