What Apartment Do I Live in?
The obvious question to arise from this is “How do I control the apartment for my threads or objects?” There is no simple answer.
Fortunately, the rules for threads are quite simple. Before a thread
can use COM, it must call one of the
CoInitialize()
or
CoInitializeEx()
functions and when it’s done
with COM, it must call CoUninitialize(); these
functions are exposed to Python by the
pythoncom
module.
CoInitialize() predates the COM threading models,
so it initializes a new single-threaded apartment for the thread.
CoInitializeEx() takes an additional parameter
that allows you to specify the threading model; thus, you must use
this function to have your thread in the free-threading apartment.
The first single-threaded apartment created (that is, the first
thread that calls either CoInitialize() or
CoInitializeEx() with the
COINIT_APARTMENTTHREADED flag) is given special
significance as we discuss later, and is known as the main
single-threaded apartment.
To hide some of this complexity, Python calls
CoInitializeEx() automatically as soon as the
pythoncom module is imported, and this is
significant for the following reasons:
The threading apartment for the first Python thread that imports the
pythoncommodule is controlled by this automatic process. By default, this thread is initialized in a single-threaded apartment, but this can be controlled by adding aco_initflagsattribute to thesysmodule before importingpythoncom(see the final sample in this ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access