ho usato Py_NewInterpreter per diversi interpreti in diversi thread, ma questo dovrebbe funzionare anche per diversi interpreti entro un filo:
Nel thread principale:
Py_Initialize();
PyEval_InitThreads();
mainThreadState = PyEval_SaveThread();
Ad ogni istanza interprete (in qualsiasi thread):
// 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
Nota che è necessario un myThreadState variabile per ogni interprete esempio!
infine al traguardo nel thread principale:
PyEval_RestoreThread(mainThreadState);
Py_Finalize();
Ci sono alcune restrizioni con l'utilizzo di diversi casi interprete (che non sembrano essere totalmente indipendenti), ma nella maggior parte dei casi questo non sembra causare problemi.
boost python utilizza python c apis. è possibile avviare l'interprete due volte chiamando Py_Initialize()? –