Python解释器作为c ++类

Amo*_*wai 9 c++ python multithreading python-embedding python-c-api

我正在努力将python嵌入到c ++中.在某些特殊情况下,我需要在同一个线程中有两个独立的解释器实例.

我可以将Python解释器包装到c ++类中并从两个或更多类实例中获取服务吗?

小智 14

我已经在不同的线程中使用Py_NewInterpreter用于不同的解释器,但是这也适用于一个线程中的几个解释器:

在主线程中:

Py_Initialize();
PyEval_InitThreads();
mainThreadState = PyEval_SaveThread();
Run Code Online (Sandbox Code Playgroud)

对于每个解释器实例(在任何线程中):

// initialize interpreter
PyEval_AcquireLock();                // get the GIL
myThreadState = Py_NewInterpreter();
... // call python code
PyEval_ReleaseThread(myThreadState); // swap out thread state + release the GIL

... // any other code

// continue with interpreter
PyEval_AcquireThread(myThreadState); // get GIL + swap in thread state
... // call python code
PyEval_ReleaseThread(myThreadState);

... // any other code

// finish with interpreter
PyEval_AcquireThread(myThreadState);
... // call python code
Py_EndInterpreter(myThreadState);
PyEval_ReleaseLock();                // release the GIL
Run Code Online (Sandbox Code Playgroud)

请注意,每个解释器实例都需要一个变量myThreadState!

最后在主线程中完成:

PyEval_RestoreThread(mainThreadState);
Py_Finalize();
Run Code Online (Sandbox Code Playgroud)

使用几个解释器实例有一些限制(它们似乎不完全独立),但在大多数情况下,这似乎不会导致问题.


Nic*_*zet 6

Callin Py_Initialize()两次不会很好,但Py_NewInterpreter可以工作,这取决于你想要做什么.仔细阅读文档,调用它时必须持有GIL.