Microsoft KB Archive/244495

= How to implement a thread-pooled apartment model COM Server in ATL =

Article ID: 244495

Article Last Modified on 5/26/2005

-

APPLIES TO

 Microsoft ActiveX Template Library 3.0, when used with:  Microsoft Visual C++ 6.0 Enterprise Edition

 Microsoft Visual C++ 6.0 Professional Edition

 Microsoft Visual C++ 6.0 Standard Edition 

-

<div class="notice_section">

This article was previously published under Q244495

<div class="summary_section">

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.

<div class="moreinformation_section">

MORE INFORMATION
The following steps are needed to create objects out of a thread pool: <ol>  Derive your CExeModule or CServiceModule class from: CComAutoThreadModule<> CExeModule : public CComAutoThreadModule<> </li> Declare DECLARE_CLASSFACTORY_AUTO_THREAD in each ATL class that can be run on an STA pool thread</li>  Declare DECLARE_NOT_AGGREGATABLE in each ATL class that can be run on an STA pool thread DECLARE_NOT_AGGREGATABLE(CMyPooledObject) </li>  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; } </li></ol>

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.

<div class="references_section">