Can you create instances of out of process COM component on different threads in parallel?

Ben van der Merwe 0 Reputation points
2023-09-14T21:55:30.9366667+00:00

The Situation

Suppose you have a simple native C++ application which calls CoInitializeEx(0, COINIT_MULTITHREADED). It then uses std::async to create a number of threads that run at the same time. Each thread routine also calls CoInitializeEx(0, COINIT_MULTITHREADED) and then calls CoCreateInstance to create an instance of an out of process (EXE) COM component.

The problem is that the calls to CoCreateInstance seem to be serialized. If you run ten threads, it takes say ten seconds. If you run five, it takes five seconds. The threads are definitely running at the same time.

If the thread function calls PeekMessage to ensure it has its own message queue, it makes no differences.

What do I know?

Determining the threading model for out of process COM servers is tricky because there are proxy objects, RPC threads, threading models, coclass settings, you name it.

It looks like for an inprocess COM server (a DLL) the threading model can be specific in the registry. But for an out of process EXE COM server, this is apparently handled by the coclass and not in the registry. CoCreate loads the EXE, and then the coclass registers itself by calling CoRegisterClassObject which passes in REGCLS_SINGLEUSE or REGCLS_MULTIPLEUSE depending on whether NewInstance (single use) is used or not. And that typically determines what subsequent CoCreateInstance calls will do, whether they return that same instance or a new one.

So that suggests that creating multiple instances of same out of process COM component must be serialized by Windows. Because a subsequent create instance call has to see what a previous one did when it called CoRegisterClassObject.

Is that true?

Is there any way to get those threads to create those instance all in parallel at the same time and not have the calls serialized?

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,519 questions
{count} votes