[Python-Dev] thread issues when embedding Python
solipsis at pitrou.net
Wed Dec 18 16:25:43 CET 2013
On Wed, 18 Dec 2013 00:19:23 +0100
Daniel Pocock <daniel at pocock.com.au> wrote:
> If a main thread does things like importing a module and obtaining a
> reference to a Python method, can those things be used by other C++
> threads or do they have to repeat those lookups?
The C++ threads must use the PyGILState API to initialize corresponding
Python thread states, and to hold the GIL.
However, you don't have to *repeat* the lookups - pointers valid in
one thread are valid in other threads, as long as you own a strong
reference to the PyObject (beware functions which return a borrowed
> Is there any logic that needs to be executed once only as each thread is
> started? (the doc suggests just PyGILState_Ensure/PyGILState_Release
> each time a thread accesses Python methods - is there anything else?)
If you use the PyGILState API, there shouldn't be anything else.
> (e.g. should users always
> explicitly call PyEval_InitThreads() in their main thread or worker
> threads or both?)
You only need to call PyEval_InitThreads() once in the main Python
More information about the Python-Dev