@tixo

Многопоточность в CPython. Как использовать PyInterpreterConfig_OWN_GIL при вызове Py_NewInterpreterFromConfig?

В версии 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();
}
  • Вопрос задан
  • 157 просмотров
Пригласить эксперта
Ответы на вопрос 1
@res2001
Developer, ex-admin
Да, похоже это оно и есть:
https://docs.python.org/3/c-api/init.html#sub-inte...
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы