[C++-sig] Re: Patch to add thread support to invoke function.

Lijun Qin qinlj at solidshare.com
Fri Sep 5 02:33:20 CEST 2003

> > it'll normally be done earlier in the very point the control
> > transferred from the 'outside world' to the python extension module,
> > in the Windows platform, this will normally at the beginning of COM
> > interface method, Window Procedure, or DLL exported function (this
> > is rare I think).
> When you say "thread acquiring" do you mean the reacquisition of the
> Python GIL and thread state?  Why would you do it any earlier than in,
> or just prior to, call_method<>?

This is because before the call_method<>, we'll normally 'touch' some python
object, so acquiring the Python GIL is needed.
Of couse, this is not always the case, but since this is common, so I think
do acquiring ealier is safter.

> A similar, but inverted thread state acquisition object should be
> used around call_method<> invocations.  My biggest question is: does
> it need a thread state, or should it just use PyEval_AcquireLock(),
> and if it *does* need a thread state, where will it come from?
According to the python document and my experiences, before a thread call
Python core, it must allocate a thread state,
If this is the main thread where Py_Initialize() is called, it's just:
PyThreadState* s_thisThread = PyThreadState_Swap(NULL);

After s_thisThread is valid, one must acquire the GIL to use the interceptor

call other Python API

In the 'invoke' case, PyEval_SaveThread/PyEval_RestoreThread is sufficient,
but in the 'call_method<>' case, one must ensure a thread state is valid,
currently, I use PyWinThreadState_Ensure() come from pywintypes.dll, which
used 'thread local storage' to save the PyThreadState*.
I'm not familiar with Unix platform, so I do not known whether it can be
used in unix platform.

Lijun Qin

More information about the Cplusplus-sig mailing list