gstate = PyGILState_Ensure();
/* Perform Python actions here. */
result = CallSomeFunction();
/* evaluate result or handle exception */
/* Release the thread. No Python API allowed beyond this point. */
Note that the
functions assume there is only one global interpreter
(created automatically by
). Python supports the creation of additional
), but mixing multiple interpreters and the
API is unsupported.
Another important thing to note about threads is their behaviour in the face of the C
call. On most systems with
, after a process forks only the thread that
issued the fork will exist. That also means any locks held by other threads will never be
released. Python solves this for
by acquiring the locks it uses internally before
the fork, and releasing them afterwards. In addition, it resets any Lock Objects in the
child. When extending or embedding Python, there is no way to inform Python of
additional (non-Python) locks that need to be acquired before or reset after a fork. OS
facilities such as
would need to be used to accomplish the same thing.
Additionally, when extending or embedding Python, calling
directly rather than
(and returning to or calling into Python) may result in a deadlock by
one of Python’s internal locks being held by a thread that is defunct after the fork.
tries to reset the necessary locks, but is not always able to.
These are the most commonly used types and functions when writing C extension code,
or when embedding the Python interpreter:
This data structure represents the state shared by a number of cooperating threads.
Threads belonging to the same interpreter share their module administration and a
few other internal items. There are no public members in this structure.
Threads belonging to different interpreters initially share nothing, except process state
like available memory, open file descriptors and such. The global interpreter lock is
also shared by all threads, regardless of to which interpreter they belong.
This data structure represents the state of a single thread. The only public data
, which points to this thread’s interpreter