How to implement a thread-pooled apartment model COM Server in ATL (244495)



The information in this article applies to:

  • The Microsoft Active Template Library (ATL) 3.0, when used with:
    • Microsoft Visual C++, 32-bit Enterprise Edition 6.0
    • Microsoft Visual C++, 32-bit Professional Edition 6.0
    • Microsoft Visual C++, 32-bit Learning Edition 6.0

This article was previously published under Q244495

SUMMARY

The Microsoft Active Template Library (ATL) allows you to define a pool of STA threads in an ATL out of process server with each object created running on its own thread. The steps in the "More Information" section of this article shows how to do this.

MORE INFORMATION

The following steps are needed to create objects out of a thread pool:
  1. Derive your CExeModule or CServiceModule class from:
    CComAutoThreadModule<>
    					
    CExeModule : public CComAutoThreadModule<>
    					
  2. Declare DECLARE_CLASSFACTORY_AUTO_THREAD() in each ATL class that can be run on an STA pool thread
  3. Declare DECLARE_NOT_AGGREGATABLE() in each ATL class that can be run on an STA pool thread
    DECLARE_NOT_AGGREGATABLE(CMyPooledObject)
    					
  4. Change the module CExeModule::Unlock() or CServiceModule::Unlock() method to call:
    CComAutoThreadModule<>::Unlock()
    						
    LONG CExeModule::Unlock()
    {
       LONG l = CComAutoThreadModule<>::Unlock();
       if (l == 0)
       {
         bActivity = true;
         SetEvent(hEventShutdown); // tell monitor that we transitioned to zero
       }
       return l;
    }
    						
If this is being done for a service, you will need to do one more step. Change the following code from:
inline void CServiceModule::Init(_ATL_OBJMAP_ENTRY* p, HINSTANCE h, UINT nServiceNameID, const GUID* plibid)
{
   CComModule::Init(p, h, plibid);
				
to:
inline void CServiceModule::Init(_ATL_OBJMAP_ENTRY* p, HINSTANCE h, UINT nServiceNameID, const GUID* plibid)
{
   CComAutoThreadModule<>::Init(p, h, plibid);
				
By default, ATL creates a pool of four threads per processor. You can change this in the _Module.Init() call in the tWinMain() function call by specifying the number of threads in the optional forth parameter. By default, CComAutoThreadModule uses CComSimpleThreadAllocator as the thread allocator. CComSimpleThreadAllocator uses a simple round robin scheme to creating objects in the thread pool.

REFERENCES

For more information lookup DECLARE_CLASS_FACTORY_AUTO_THREAD() and CComAutoThreadModule and the Microsoft Developer's Network (MSDN).

For more information, click the following article number to view the article in the Microsoft Knowledge Base:

202128 FIX: ATL EXE server based on CComAutoThreadModule may hang on registration


Modification Type:MajorLast Reviewed:5/26/2005
Keywords:kbArchitecture kbhowto kbLocalSvr kbService kbThread KB244495 kbAudDeveloper