Skip to main content

COM Threading Models

· 2 min read

COM Threading Models / Apartment Model

Definition: Multithreading in COM is referred to as the apartment model in COM

Apartment

The COM apartment is a conceptual entity that allows us to think about components and their clients in a logical way

  • An apartment is not a thread, but a thread belongs to only one apartment.

  • An apartment is not an instance of a COM object, but each COM instance belongs to only one apartment.

  • A process can have one or more apartments, depending on its implementation.

  • Apartments are created or entered by calling the CoInitialize or CoInitializeEx function. Each thread that calls CoInitialize(0) or CoInitializeEx( 0, COINIT_APARTMENTTHREADED )

  1. STA (Single Threaded Apartment) : Only One thread can join this Apartment.
  2. MTA (MultiThreaded Apartment): Multiple threads can join this Apartment.

Differences between STA and MTA

NoFeatureSTAMTA
1Synchronization provided by COMYESNO
2Uses Windows message queuesYESNO
3Can have multiple threads in an apartmentNOYES
4Must marshal interface pointers between the threads in the same apartmentN/AYES
5Must marshal interface pointers between apartmentsYESYES
6Must call Coinitialize() in every thread that uses a COM ServiceYESYES
7PerfomanceSlowFast

NOTE: ATL object wizard allows you to set the threading model. The values can be

Threading ModelDescription
Single / No ValueObject knows nothing about threads
ApartmentSTA
FreeMTA
BothBoth STA & MTA