MFC › 7. Data, System and Interop
Threads and Timers
Worker threads, UI threads, SetTimer and synchronization.
Explanation
Timers: SetTimer(id, milliseconds, nullptr) makes Windows send WM_TIMER to the window about every interval; handle it with ON_WM_TIMER() and OnTimer(UINT_PTR nIDEvent); stop with KillTimer(id). Timers run on the UI thread, are not precise (±15 ms) and are low priority, so they are for animations, clocks and polling, not measurement.
Worker threads: AfxBeginThread(ThreadProc, param) starts a function UINT __cdecl ThreadProc(LPVOID pParam) on a new thread. It returns a CWinThread*. By default MFC deletes the CWinThread object when the thread ends (m_bAutoDelete), so don’t touch the pointer later unless you create the thread suspended, set m_bAutoDelete = FALSE, and call ResumeThread().
UI threads: derive from CWinThread, override InitInstance, and the thread gets its own message loop (it can own windows). Use rarely.
Golden rule: never touch the UI from a worker thread. Windows and controls belong to the thread that created them. Instead the worker posts a message to the window: ::PostMessage(hWnd, WM_APP_PROGRESS, percent, 0) (asynchronous, safe; pass the HWND, not a CWnd*) and the UI thread handles it with ON_MESSAGE(WM_APP_PROGRESS, &Handler). SendMessage blocks until the handler finishes, which can deadlock.
Synchronization classes: CCriticalSection + CSingleLock (RAII), CMutex, CSemaphore, CEvent (SetEvent, ResetEvent, Lock() / WaitForSingleObject). Wait for a thread to finish with ::WaitForSingleObject(pThread->m_hThread, INFINITE).
Since C++11 you can use std::thread, std::mutex and std::atomic instead (Threads, Mutexes and Atomics); the post-a-message-to-the-UI rule stays.
Example
Two workers updating a shared counter safely, and a stop signal:
#include <afxwin.h>
#include <afxmt.h> // CCriticalSection, CSingleLock, CEvent
#include <iostream>
struct Shared {
CCriticalSection lock;
int counter = 0;
CEvent stopRequested; // manual-reset event
Shared() : stopRequested(FALSE, TRUE) {}
};
UINT AddThousand(LPVOID pParam) { // worker function signature
Shared* s = static_cast<Shared*>(pParam);
for (int i = 0; i < 1000; ++i) {
CSingleLock guard(&s->lock, TRUE); // locked here, unlocked at end of scope (RAII)
++s->counter;
}
return 0; // thread exit code
}
UINT WaitForStop(LPVOID pParam) {
Shared* s = static_cast<Shared*>(pParam);
DWORD r = ::WaitForSingleObject(s->stopRequested, 5000); // wakes when the event is set
return r == WAIT_OBJECT_0 ? 1 : 0;
}
int _tmain() {
if (!AfxWinInit(::GetModuleHandle(nullptr), nullptr, ::GetCommandLine(), 0)) return 1;
Shared shared;
CWinThread* t1 = AfxBeginThread(AddThousand, &shared, THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED);
CWinThread* t2 = AfxBeginThread(AddThousand, &shared, THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED);
t1->m_bAutoDelete = FALSE; // we want to wait on the thread object ourselves
t2->m_bAutoDelete = FALSE;
t1->ResumeThread();
t2->ResumeThread();
::WaitForSingleObject(t1->m_hThread, INFINITE);
::WaitForSingleObject(t2->m_hThread, INFINITE);
std::wcout << L"counter = " << shared.counter << L"\n";
delete t1;
delete t2; // required because m_bAutoDelete is FALSE
CWinThread* waiter = AfxBeginThread(WaitForStop, &shared, THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED);
waiter->m_bAutoDelete = FALSE;
waiter->ResumeThread();
shared.stopRequested.SetEvent(); // signal the other thread
::WaitForSingleObject(waiter->m_hThread, INFINITE);
DWORD code = 0;
::GetExitCodeThread(waiter->m_hThread, &code);
std::wcout << L"waiter saw stop signal: " << code << L"\n";
delete waiter;
return 0;
}
The standard pattern for a dialog: do the long work on a thread and report progress by posting messages.
#include <afxwin.h>
#include <afxcmn.h>
#include <atomic>
#define WM_APP_PROGRESS (WM_APP + 1)
#define WM_APP_DONE (WM_APP + 2)
class CWorkDlg : public CDialog {
public:
enum { IDD = IDD_WORK };
explicit CWorkDlg(CWnd* pParent = nullptr) : CDialog(IDD, pParent), m_cancel(false), m_pThread(nullptr) {}
protected:
CProgressCtrl m_progress;
std::atomic<bool> m_cancel; // read by the worker, written by the UI
CWinThread* m_pThread;
void DoDataExchange(CDataExchange* pDX) override {
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_PROGRESS, m_progress);
}
static UINT Worker(LPVOID p) {
CWorkDlg* dlg = static_cast<CWorkDlg*>(p);
HWND hWnd = dlg->GetSafeHwnd(); // copy the HWND; don't use CWnd* on this thread
for (int i = 1; i <= 100 && !dlg->m_cancel; ++i) {
::Sleep(50); // pretend to work
::PostMessage(hWnd, WM_APP_PROGRESS, i, 0); // asynchronous, thread-safe
}
::PostMessage(hWnd, WM_APP_DONE, 0, 0);
return 0;
}
afx_msg void OnStart() {
m_cancel = false;
m_progress.SetRange(0, 100);
m_pThread = AfxBeginThread(Worker, this);
}
afx_msg void OnCancelWork() { m_cancel = true; }
afx_msg LRESULT OnProgress(WPARAM percent, LPARAM) { m_progress.SetPos(static_cast<int>(percent)); return 0; }
afx_msg LRESULT OnDone(WPARAM, LPARAM) { AfxMessageBox(_T("Finished")); return 0; }
afx_msg void OnTimer(UINT_PTR id) { if (id == 1) SetWindowText(CTime::GetCurrentTime().Format(_T("%H:%M:%S"))); }
afx_msg void OnClose() { m_cancel = true; KillTimer(1); CDialog::OnClose(); }
BOOL OnInitDialog() override { CDialog::OnInitDialog(); SetTimer(1, 1000, nullptr); return TRUE; }
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(CWorkDlg, CDialog)
ON_BN_CLICKED(IDC_START, &CWorkDlg::OnStart)
ON_BN_CLICKED(IDC_CANCEL_WORK, &CWorkDlg::OnCancelWork)
ON_MESSAGE(WM_APP_PROGRESS, &CWorkDlg::OnProgress)
ON_MESSAGE(WM_APP_DONE, &CWorkDlg::OnDone)
ON_WM_TIMER()
ON_WM_CLOSE()
END_MESSAGE_MAP()
Common pitfalls
- Touching UI from a worker thread: calling
m_edit.SetWindowText()on another thread may appear to work, then deadlock or assert (MFC’s handle maps are per thread). Post a message. - Passing a
CWnd*/stack variable to a thread that outlives it. Pass anHWNDor heap data. - Closing the dialog while the worker still runs: signal it to stop and wait for it (or the worker posts to a destroyed window; posting to an invalid
HWNDis harmless but don’t deref theCWnd). - A thread object with
m_bAutoDelete = TRUEis invalid after the thread ends. Don’t keep the pointer. - Deadlock:
SendMessagefrom a worker while the UI thread waits for the worker. UsePostMessage. SetTimerwithnullptrcallback requires the window to handleWM_TIMER; forgettingKillTimerleaks the timer.- Data shared between threads needs a lock or atomic. Reading an
intwhile another thread writes is a data race. - The
CStringclass is thread-safe for separate objects, but sharing one object between threads is not.
Legacy vs modern
The same architecture today: std::thread/std::async, std::atomic, std::mutex plus a message post to the UI. See Threads, Mutexes and Atomics and Coroutines.
Exercises
1. Why does the worker copy the HWND before starting its loop?
An HWND is a plain handle that is safe to use from any thread with PostMessage. The CWnd object (and its handle map) is not thread-safe and belongs to the UI thread.