Click here to Skip to main content
12,405,543 members (54,741 online)
Click here to Skip to main content
Add your own
alternative version


30 bookmarked

Threads And Timers

, 26 Jan 2004
Rate this:
Please Sign up or sign in to vote.
Adding a WM_TIMER message to CWinThreads.


In this project and in the source files, there is a base class to CWinThread class that will provide you with WM_TIMER messages to your threads. Since WM_TIMER messages are reserved for window objects only, this is a bit tricky to perform. I did this because I was in need of threads that could react to timers but I had lots of threads (100's) to manage and they all read there configuration from the database and set timers based on that configuration. Some threads had 1 timer and other threads had 100's of timers. I needed a way to manage all these timers and events.

Using the code

This class is derived from the standard MFC CWinThread class. m_autoremove will remove all the timers outstanding if you don't. You can turn it off by setting the m_autoremove to false. There are 2 methods AddTimer() and RemoveTimer(). Simple!

// WinTimerThread.h
class CWinTimerThread : public CWinThread

        bool    m_autoremove;
        UINT_PTR AddTimer(UINT uElapse);
        BOOL RemoveTimer(UINT_PTR idEvent);

// WinTimerThread.cpp
// Static declarations
static CMapPtrToPtr g_MapTimerID_TO_CWinThreadPtr;

static void CALLBACK TimerProc(
    HWND hwnd,         // handle to window
    UINT uMsg,         // WM_TIMER message
    UINT_PTR idEvent,  // timer identifier
    DWORD dwTime       // current system time 
    CWinThread* pThread;

    if (g_MapTimerID_TO_CWinThreadPtr.Lookup((void *) idEvent, (void*&) pThread))
        pThread->PostThreadMessage(WM_TIMER, idEvent, dwTime);
// Class 

    m_autoremove = true;

    // check if autoremove is activated
    if (!m_autoremove)
    // declare local variables
    POSITION pos;
    UINT_PTR idEvent;
    CWinThread* pThread;

    //get the starting point in the list of timer events
    pos = g_MapTimerID_TO_CWinThreadPtr.GetStartPosition();
    //loop while there are list items
    while (pos)
        // get timer event entry
            (void *&) idEvent, (void*&) pThread);
        // check if the idevent is refering to this object
        if (pThread == this)

UINT_PTR CWinTimerThread::AddTimer(UINT uElapse)
    UINT_PTR idEvent;

    idEvent = ::SetTimer(NULL, NULL, uElapse, (TIMERPROC) TimerProc);
    g_MapTimerID_TO_CWinThreadPtr.SetAt((void *) idEvent, this);
    return idEvent;
BOOL CWinTimerThread::RemoveTimer(UINT_PTR idEvent)
    ::KillTimer(NULL, idEvent);
    return g_MapTimerID_TO_CWinThreadPtr.RemoveKey((void *) idEvent);

Below is how to use the new CWinTimerThread.

// MyThread.h
#include "WinTimerThread.h"

#if !defined(MYTHREAD_H)
#define MYTHREAD_H
#pragma once

class CMyThread : public CWinTimerThread

        virtual BOOL InitInstance();
        virtual int ExitInstance();

        void SetLogWindow(CWnd* pWnd);

        CWnd* m_pLogWnd;
        void LogMessage(CString& logmsg);
        void OnTimer(WPARAM idEvent, LPARAM dwTime);

#endif // MYTHREAD_H

Notice that all you have to do is call AddTimer() anywhere in the thread and specify the amount of milliseconds, and you're done. The clean up is done for you so you don't even have to worry about it.

// MyThread.cpp
#include "stdafx.h"
#include "MyThread.h"

#ifdef _DEBUG
#define new DEBUG_NEW



BEGIN_MESSAGE_MAP(CMyThread, CWinTimerThread)

BOOL CMyThread::InitInstance()
    return TRUE;

Points of Interest

Posting the WM_TIMER message to the thread should be safe since the numeric value is 0x113, well below WM_USER = 0x400. This is very compatible to the original SetTimer(), KillTimer() and OnTimer(idEvent, dwTime).

Also note that the message to the thread is ON_THREAD_MESSAGE() not the ON_MESSAGE() macro.


Version 1.0


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

David A. Jones
Web Developer
Canada Canada
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralExcellent article; one small quibble on thread safety Pin
Hal Berman29-May-08 6:06
memberHal Berman29-May-08 6:06 
This class fit the bill perfectly for solving a problem with hung threads in a web server. Thanks for the code and the explanations.

One thing I'll mention for the benefit of others who might use this is that the methods of CWinTimerThread that manipulate the map (and TimerProc, too) should be made thread safe so that the map isn't modified or read by more than one thread at a time. One way to do this is to derive a class based on the map that provides a critical section:

class CMapPtrToPtrSafe : public CMapPtrToPtr
public:	CCriticalSection	m_CritSec;  // to synchronize access to class
static CMapPtrToPtrSafe g_MapTimerID_TO_CWinThreadPtr;
Then, in each of the methods of CWinTimerThread that access the map (and in the TimerProc callback, too), the critical section can be locked before the map is accessed and unlocked when done. For example:

static void CALLBACK TimerProc(
	HWND hwnd,         // handle to window
	UINT uMsg,         // WM_TIMER message
	UINT_PTR idEvent,  // timer identifier
	DWORD dwTime       // current system time 
	CWinThread* pThread;
	if (g_MapTimerID_TO_CWinThreadPtr.Lookup((void*) idEvent, (void*&) pThread))
		pThread->PostThreadMessage(WM_TIMER, idEvent, dwTime);
Thanks again!
Generalfrequency of running process Pin
mehmetned17-Jul-06 22:53
membermehmetned17-Jul-06 22:53 
GeneralRe: frequency of running process Pin
David A. Jones18-Jul-06 4:23
memberDavid A. Jones18-Jul-06 4:23 
GeneralCWinThread and SetTimer Pin
kumar_subrahmanya7-Jul-06 1:58
memberkumar_subrahmanya7-Jul-06 1:58 
GeneralRe: CWinThread and SetTimer [modified] Pin
David A. Jones12-Jul-06 5:20
memberDavid A. Jones12-Jul-06 5:20 
Generalerror while creating class derived from CWinThread Pin
VC++error11-Jul-05 10:47
sussVC++error11-Jul-05 10:47 
GeneralOnTimer() Pin
medlar12-Jun-05 22:27
membermedlar12-Jun-05 22:27 
GeneralChanging the AddTimer Pin
Tom Wright10-Mar-05 10:10
memberTom Wright10-Mar-05 10:10 
GeneralRe: Changing the AddTimer Pin
Tom Wright10-Mar-05 11:00
memberTom Wright10-Mar-05 11:00 
GeneralRequired in Visual Studio 6.0 Env. Pin
sudiptam29-Sep-04 1:27
membersudiptam29-Sep-04 1:27 
GeneralRe: Required in Visual Studio 6.0 Env. Pin
David A. Jones1-Oct-04 15:12
memberDavid A. Jones1-Oct-04 15:12 
QuestionIs it really possible to create 100's of Timers? Pin
Persia26-Feb-04 2:17
memberPersia26-Feb-04 2:17 
AnswerRe: Is it really possible to create 100's of Timers? Pin
David A. Jones26-Feb-04 4:43
memberDavid A. Jones26-Feb-04 4:43 
Generalversion 7.10 Pin
Gopal Krishna15-Apr-04 3:46
sussGopal Krishna15-Apr-04 3:46 
GeneralRe: version 7.10 Pin
David A. Jones16-Apr-04 2:53
memberDavid A. Jones16-Apr-04 2:53 
AnswerRe: Is it really possible to create 100's of Timers? Pin
David A. Jones1-Oct-04 15:09
memberDavid A. Jones1-Oct-04 15:09 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160721.1 | Last Updated 27 Jan 2004
Article Copyright 2004 by David A. Jones
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid