Threading Classes
Multiple threads can pose a problem for COM developers. Our threading classes target the COM worker thread use case, where apartments must be initialized correctly and interface pointers may need to be marshaled into the worker thread procedure. These are not pooling classes, but primarily encapsulations of common client usage.
Suppose you have a COM object in your main thread. Now, let’s suppose that you want to launch a worker thread to perform some background task on that object. With our threading classes, you can declare the thread procedure with typed arguments, not just a void*, then create a COtlThreadFunction object that wraps it all up. The thread is constructed in a suspended state, and can be executed using the Start() function. Here is some code from the InterfaceToken sample that illustrates this:
 
COtlThreadFunction mta(functokII, COINIT_MULTITHREADED);
mta.Start();
You can create thread objects on the heap or on the stack. The destructor does not return until the thread is complete and its handle is signaled. You can also use your own thread synchronization methods by accessing the encapsulated thread handle directly. Between construction and Start, you can make priority adjustments by using the thread handle directly. The handle and thread ID are available through the COtlThreadFunction m_hthread and m_dwTID public data members.
COtlThreadFunction relies on an OTL functor object, which is described in “Functors”. The preceding sample code passes a previously constructed functor object (functokII) to the thread object constructor.
The COM apartment is initialized and uninitialized transparently by the COtlThreadFunction object. You declare the apartment type in the thread object constructor with a standard COINIT_XXX constant. Apartment threading is the default. Interface pointers can be wrapped in a COtlInterfaceToken object (one per interface pointer) and passed directly to the thread procedure.