Click here to Skip to main content
12,882,820 members (36,851 online)
Click here to Skip to main content
Add your own
alternative version


77 bookmarked
Posted 30 May 2006

Thread classes for WTL

, 30 May 2006
Rate this:
Please Sign up or sign in to vote.
Presents a small set of ATL/WTL classes that simplify working with threads.


While ATL and WTL offer useful wrapper classes for most of the various objects a Win32 HANDLE can refer to, threads still have to be created and controlled using the API functions and handles directly. Admittedly, this is not a hard thing to do, but a clean object-oriented design can often help in avoiding bugs in multi-threaded applications.

The class collection I am going to present has often proved very useful to me. It contains handle wrappers for threads, as well as base classes that help implement worker and GUI threads.

The thread handle wrapper classes

There is not much to say about these classes. In the style usually followed by WTL, CThreadT is a wrapper template class around a thread handle, which offers most of the Win32 API functions that take a thread handle as methods.

More conveniently, one will usually use the template instantiations CThread and CThreadHandle: CThread will close the thread handle when it is destroyed, while CThreadHandle won't.

Creating a thread

Thread creation is implemented as the static method CThreadT::Create, which is a wrapper around _beginthreadex (or CreateThread, if the "minimal use of CRT" option is set).

// ...
CThread thread = CThread::Create( (LPTHREAD_START_ROUTINE) 
                                   MyThreadProc, pParam );
// ...

Additional methods of CThread and CThreadHandle

  • CThreadT(HANDLE=NULL, DWORD=0) wraps a CThread instance around the given thread handle and thread ID.
  • There is also a copy constructor, which will call DuplicateHandle on the given handle.
  • The thread handle and ID can be retrieved with GetHandle() and GetId().
  • The methods Open, GetPriority, SetPriority, GetExitCode, GetThreadTimes, IsIOPending, Resume, Suspend, Terminate, and Exit are all wrappers around the respective API functions, their names mostly net of the word "thread".
  • The method Join performs a WaitForSingleObject on the thread handle.

GUI Threads

GUI threads are different from general worker threads in that they have a message queue. This means that we can post messages to a GUI thread using PostThreadMessage.

The template class CGuiThreadT, and its instantiations CGuiThread and CGuiThreadHandle, are just like the CThreadT classes, with an additional method PostThreadMessage for this end.

Causing a GUI thread to quit is usually a matter of posting the WM_QUIT message to its queue. This is done by the PostQuitMessage method. However, this method does not wrap the API of the same name, as the latter posts WM_QUIT to the calling thread, which is not always the same.

The thread implementation classes

As ATL and WTL often differentiate between a handle to an object and its implementation (compare CWindow and CWindowImpl), I have chosen the same design for my thread classes (though the two cases are not perfectly comparable). The class CThreadImpl provides the skeleton for a thread "implementation" class.

Derive your thread class from CThreadImpl<T> and implement the Run method:

<PRE lang=c++>class CWorkerThread : public CThreadImpl<CWorkerThread> { public: DWORD Run() { // Do something useful... return 0; } }; // // In some other function, that is called from your main thread: CWorkerThread* pThread = new CWorkerThread;

The return value of Run is the thread's exit code, like in the standard Win32 ThreadProc.

If you create an instance of CWorkerThread, it will start running immediately. If you want to start it later, you can pass CREATE_SUSPENDED to CThreadImpl's constructor and call Resume later.

Note that the constructor runs in the creating thread, so some of the thread initialization may have to be moved to the run method.


class CWorkerThread : public CThreadImpl<CWorkerThread>
    : CThreadImpl<CWorkerThread>(CREATE_SUSPENDED)
  { }

  BOOL Initialize()
    // Perform initialization.
    return TRUE;

  DWORD Run()
    if ( !Initialize() )
      return 1;

    // Do something useful...
    return 0;

// In some other function, that is called from your main thread:

CWorkerThread* pThread = new CWorkerThread;

Implementation of GUI threads

The class CGuiThreadImpl uses the WTL class CMessageLoop to manage a message loop. However, since CAppModule wants to know about all CMessageLoops in the process, this means you have to pass a pointer to your CAppModule instance in the constructor.

To implement a GUI thread, derive your class from CGuiThreadImpl and (optionally) override the following methods:

  • BOOL InitializeThread() to perform thread initialization. This is, for example, a good place to create windows. Return FALSE to stop the thread.
  • void CleanupThread(DWORD) to perform cleanup tasks. The DWORD parameter is the exit code from the message loop.

Handling messages

You can also add a message map to your thread class using the standard macro, BEGIN_MSG_MAP. However, these will only be called for messages that are not directed to a window, i.e., where the hWnd parameter is NULL.

Remember that you can access the thread's message loop using CAppModule::GetMessageLoop(), so you can, for example, install additional CMessageFilters. The place to do this would be the InitializeThread and CleanupThread methods.


The following example shows a simple GUI thread class which creates a timer and responds to the WM_TIMER message.

#include "Thread.h"

class CTimerThread : public CGuiThreadImpl<CTimerThread>

  UINT_PTR m_nTimerId;

  CTimerThread(CAppModule* pModule)
    : CGuiThreadImpl<CTimerThread>(pModule)
  { }

  BOOL InitializeThread()
     m_nTimerId = ::SetTimer(NULL, 0, 1000, NULL);
     return (m_nTimerId != 0);

  void CleanupThread(DWORD)
    ::KillTimer(NULL, m_nTimerId);

    return 0;

The "timer thread" has to be created and stopped from the main thread:

class CMainFrame : ...
  CTimerThread* m_pTimerThread;

  // ...

    // ...
    m_pTimerThread = new CTimerThread(&_Module);
    // ...

  void OnDestroy()
    // ...
    delete g_pTimerThread;
    // ...

Using the classes

All the thread classes are contained in a single header file, Thread.h, which you can download using the link given at the start of the article. To facilitate the classes, you just need to include Thread.h in your project.

If you would like to use the classes in a ATL-but-not-WTL project, you will need to remove all the GUI-thread related sections from the code. The other classes (CThreadT and CThreadImpl) will work with "pure" ATL as well.


Using the set of classes presented in this article, it is possible to achieve a cleaner, more object-oriented design for multithreaded applications. The template design similar to the one found in other ATL/WTL classes makes it easy to understand and integrate.

Revision history

  • 06-30-2006
    • Original article.
  • 06-31-2006
    • CThreadT::Create now calls _beginthreadex if possible (depending on _ATL_MIN_CRT).
    • Added method CThreadT::Exit.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Till Krullmann
Software Developer (Senior) Accenture
Germany Germany
Till is living in Munich, Germany, and works as an IT consultant. His current focus is mainly on Java Enterprise projects, but tries to stay up to date with the latest .NET developments.

You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
Member 199691720-Apr-12 6:50
memberMember 199691720-Apr-12 6:50 
GeneralConstructor Pin
barto23-Nov-10 10:32
memberbarto23-Nov-10 10:32 
GeneralRe: Constructor Pin
Till Krullmann27-Nov-10 23:52
memberTill Krullmann27-Nov-10 23:52 
GeneralATL library DOES have a thread wrapped class:CWorkerThread Class Pin
David_LoveCpp13-Apr-10 20:16
memberDavid_LoveCpp13-Apr-10 20:16 
GeneralRe: ATL library DOES have a thread wrapped class:CWorkerThread Class Pin
Till Krullmann28-Nov-10 0:12
memberTill Krullmann28-Nov-10 0:12 
Generalerror C2488: '_ThreadProcThunk' Pin
Member 92643716-Mar-09 5:08
memberMember 92643716-Mar-09 5:08 
GeneralProgress dialog with your thread Pin
rafranco7-Feb-07 6:41
memberrafranco7-Feb-07 6:41 
GeneralRe: Progress dialog with your thread Pin
Till Krullmann7-Feb-07 7:10
memberTill Krullmann7-Feb-07 7:10 
Questiondead lock? Pin
Satie Zhao7-Jun-06 22:13
memberSatie Zhao7-Jun-06 22:13 
I used the CGuiThreadImpl help class and your timer example to write a test program on win2003 and vc2005, and found deadlock undefinitely.

I created a window which calls your example , immediately the window was destroyed(Consecutively called the PostQuitMessage() , Join() in CMainFrame::OnDestroy)

I found when PostQuitMessage is executed the timer thread may not yet step into its message loop . At times the WM_QUIT message is not posted to the thread message loop, so WaitForSingleObject will not return forever and the application is deadlocked.

I hope you can get what i said.

AnswerRe: dead lock? Pin
VedicAnand3-Dec-09 16:42
memberVedicAnand3-Dec-09 16:42 
QuestionCOM? Pin
JBurkey1-Jun-06 7:20
memberJBurkey1-Jun-06 7:20 
AnswerRe: COM? Pin
olegxxx5-Jun-06 20:13
memberolegxxx5-Jun-06 20:13 
GeneralGood stuff Pin
yafan30-May-06 14:15
memberyafan30-May-06 14:15 
GeneralRe: Good stuff Pin
Nemanja Trifunovic31-May-06 1:21
memberNemanja Trifunovic31-May-06 1:21 
GeneralRe: Good stuff Pin
Till Krullmann31-May-06 1:55
memberTill Krullmann31-May-06 1:55 
GeneralRe: Good stuff Pin
Nemanja Trifunovic31-May-06 2:41
memberNemanja Trifunovic31-May-06 2:41 
GeneralRe: Good stuff Pin
Till Krullmann31-May-06 3:14
memberTill Krullmann31-May-06 3:14 
GeneralRe: Good stuff Pin
Pablo Aliskevicius5-Jun-06 21:18
memberPablo Aliskevicius5-Jun-06 21:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170422.1 | Last Updated 30 May 2006
Article Copyright 2006 by Till Krullmann
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid