c++multithreadingvisual-studiocomapartments

Using c++11 <thread> with COM threading apartments on Windows - hints, tips, pitfalls?


I am working on a Windows application that uses multiple USB sound interfaces with ASIO drivers. Each driver exposes an in-process COM server and has to be run using a Single Threaded Apartment.

My plan is to run each in it's own STA responsible for processing callbacks and controlling the devices while the heavy lifting is done from a Multiple Threaded Apartment making use of however many hardware threads the processor cores can provide, and using whatever the thread and future headers can supply to make the code manageable.

What I am wanting to know is if the standard C++ multi-threading implementations (particularly Visual Studio) play nice with the COM multi-threading requirements (which I'm still researching - marshaling between apartments is still a mystery)? Or will I get less friction from designing some sort of framework to wrap the appropriate Windows platform API calls?


Solution

  • Whether you create a thread via a framework call like std::thread or _beginthreadex(), or if you just call the Win32 CreateThread() directly, ultimately it all ends up in the same place within the OS.

    COM is a system component, as are threads. They are independant of any particular compiler, but they do depend on the OS. So, in the case of using COM in threads, every thread is individually responsible for explicitly calling CoInitialize/Ex() to establish which apartment it is to be associated with, whether that be an STA, or the MTA. As well as explicitly calling CoUninitialize() when COM is no longer needed.

    This can be done equally in any of the above mentioned thread-management calls.