[python-win32] Threads, COM, gc

Thomas Heller theller at ctypes.org
Thu May 26 17:14:46 CEST 2011


I have to fix a tricky problem that we recently discovered in our
software.

We have a multithreading Python program that uses a lot of COM objects.
COM objects have the requirement that they must only be used in
the COM apartment where they have been created.  Different threads often
or even most of the time run in different apartments.

This requirement is easy to fulfill (if the programmer is careful),
but there is one exception:

If the COM object is part of a reference cycle of some other Python
objects, then it is not destroyed when it goes out of scope, instead
it is destroyed when the Python cycle gc runs.

The garbage collector can run in any thread; so the cleanup of the
COM object may happen in some arbitrary thread.  This is not allowed,
and in some circumstances the program hangs or maybe it even crashes.

So, it must be ensured that the cleanup of the COM objects happen
in the same thread where they have been created.

Does anyone have some ideas how this could be approached?

Thanks,
Thomas



More information about the python-win32 mailing list