Can two threads use the same python built-in interpreter at the same time?

The name has this, but here are some developments. Suppose the main thread spawns another thread, where some code is loaded into the python interpreter, and then another thread is called, which executes another code through the same python interface (via PyImport or PyRun). Is such a scenario feasible?

+5
source share
1 answer

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.

+2
source

All Articles