[python-win32] The GIL and COM

Mark Hammond skippy.hammond at gmail.com
Wed Jan 21 22:59:40 CET 2009

On 22/01/2009 3:33 AM, Brad Johnson wrote:
> I have embedded the Python interpreter into a COM application. In this
> application, I create worker threads that execute Python code.
> I marshal some COM objects that live in the UI thread of the application over to
> the worker thread and wrap them with EnsureDispatch() for use in the new thread.
> Meanwhile, the UI thread sometimes has work to do with Python. It attempts to
> acquire the GIL and releases it when done.

How is the UI thread written and how does it attempt to use the GIL?

> However, while it is waiting for the
> GIL in the UI thread (when the worker thread has it), it is locked into a
> WaitForSingleObject call (some layers below PyGILState_Ensure).

Obviously the GIL can only be held by one thread at a time.  The 
question then is why your worker thread isn't periodically releasing the 
GIL so the UI thread can grab it.

> Anyone that uses COM knows that this is not a COM-safe wait, and message pumping
> will not continue. In other words, if my worker thread ever wants to marshal a
> call back into the UI thread, it will deadlock.

That is not true - it is very easy to demonstrate a multi-threaded 
program in Python that marshals COM objects between threads and doesn't 
deadlock.  Similarly, it is very easy to write a multi-threaded GUI app 
(assuming you follow the windows threading GUI rules) which face an 
almost identical problem (one thread must be in a message loop while the 
others are not)

The GIL handles this situation just fine, so long as all C code does the 
right thing.  I don't think we understand you problem well enough to 
give you any answers yet though.



More information about the python-win32 mailing list