COM now has five types of Apartment:
1. Legacy
2. STA
3. Free
4. Both
5. Neutral
I'll discuss the Apartment in this article.
COM Objects living in Apartment will be protected by COM, any other calls for this object will be serialized by the COM. If there are concurrent threading in your application and you also don't want to the complicated multi-thread concurrency, you may get to love the Apartment model.
Here are some points of the Apartment modle:
1. Each Single Apartment only contains one thread.
2. Each thread should call ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
to join the STA.
3. If you want to call the STA COM object living in other STA, you need to marshal your pointer.
4. Each STA may contain more than one COM objects.
5. At one time a STA allows only one thread running.
The code for COM object is simple. Here is I just list the code snippet for the client.
#include <iostream>
using namespace std;
#import "CarDemo.dll" no_namespace
void ThreadFunc(void *);
//IFreeCar * pCar;
//IFreeCar * pCar;
ICar * pCar;
int _tmain(int argc, _TCHAR* argv[])
{
::CoInitializeEx(NULL, COINIT_MULTITHREADED);
{
ICar * pCar;
::CoCreateInstance(__uuidof(Car) , NULL, CLSCTX_INPROC_SERVER , __uuidof(ICar) , (void**)&pCar);
IStream* interfaceStream1;
IStream* interfaceStream2;
CoMarshalInterThreadInterfaceInStream(__uuidof(ICar), pCar, &interfaceStream1);
CoMarshalInterThreadInterfaceInStream(__uuidof(ICar), pCar, &interfaceStream2);
HANDLE hThread[2];
hThread[0] = (HANDLE)::_beginthread(ThreadFunc, 0, (void*)interfaceStream1);
hThread[1] = (HANDLE)::_beginthread(ThreadFunc, 0, (void*)interfaceStream2);
::WaitForMultipleObjects(2, hThread, true, INFINITE);
pCar->Release();
}
int iVal;
cin>>iVal;
::CoUninitialize();
return 0;
}
void ThreadFunc(LPVOID lpParameter)
{
::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
{
IStream* pStream = reinterpret_cast<IStream*>(lpParameter);
ICar * pCar;
CoGetInterfaceAndReleaseStream(pStream, __uuidof(ICar), reinterpret_cast<void**>(&pCar));
pCar->Drive(3);
pCar->Release();
}
::CoUninitialize();
}
Here is some helpful links for you to understand the STA better:
http://support.microsoft.com/default.aspx?scid=kb;en-us;172314
http://support.microsoft.com/kb/206076