If I follow what you ask, then yes, you can do it, but the Python interpreter itself is not completely thread protected. To get around this, you need to make sure that each thread gets a GIL interpreter before invoking any Python code, and then releases it later. Each thread must perform the following operations when executing Python code:
PyGILState_STATE gstate; gstate = PyGILState_Ensure(); // Do any needed Python API operations, execute python code // Release the GIL. No Python API allowed beyond this point. PyGILState_Release(gstate);
Also, after starting the Python interpreter, you must do the following to ensure that the / GIL threads are correctly initialized:
if (! PyEval_ThreadsInitialized()) { PyEval_InitThreads(); }
For more information, see Uncreated Python Themes .
As mentioned in the comments, it is worth noting that this is actually just serialization of access to the interpreter, but this is best if you assume that you are using the Python implementation on CPython.
source share