100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
C++

Multithreading in MFC

How MFC wraps Win32 threading into CWinThread, worker vs. UI threads, and the synchronization classes (CCriticalSection, CMutex, CEvent, CSemaphore) used to coordinate them safely.

Advanced MFCIntermediate10 min readJul 10, 2026
Analogies

Worker Threads vs. UI Threads

MFC exposes two flavors of thread through the CWinThread class: worker threads, created with AfxBeginThread(AFX_THREADPROC, pParam, ...), which run a plain controlling function with no message pump; and UI threads, created by passing a CWinThread-derived CRuntimeClass, which get a full message loop (CWinThread::Run) and can own windows, dialogs, and idle processing. A worker thread is the right tool for a background computation such as compressing a file or querying a database, because it never needs to receive WM_ messages. A UI thread is required whenever the thread itself creates and owns HWNDs, since every window's messages must be pumped on the thread that created it.

🏏

Cricket analogy: A worker thread is like the groundstaff mowing the pitch between innings - focused, self-contained, no interaction with the umpire's signals - while a UI thread is like the on-field umpire who must continuously watch for and respond to appeals, exactly as a UI thread must pump window messages.

Creating and Terminating Threads

AfxBeginThread returns a CWinThread pointer whose m_bAutoDelete flag defaults to TRUE, meaning the CWinThread object deletes itself the instant the thread function returns - so holding onto that pointer after the thread may have exited is dangerous. If code needs to wait for the thread or inspect its exit code afterward, it must set m_bAutoDelete to FALSE immediately after creation (before resuming a suspended thread) and call delete on the CWinThread object itself once done. Threads should be asked to exit cooperatively, typically by setting a shared flag or signaling a CEvent that the worker checks periodically, rather than being forcibly killed with TerminateThread, which can leave CRT locks, heap state, or MFC's own internal structures corrupted.

🏏

Cricket analogy: Setting m_bAutoDelete to FALSE is like a team management insisting on a post-match report from the twelfth man before he's released from the squad, rather than letting him walk off immediately once his spell of overs ends.

Synchronization Objects

MFC wraps the Win32 synchronization primitives in classes derived from CSyncObject: CCriticalSection for fast intra-process mutual exclusion, CMutex for cross-process locking (optionally named), CEvent for signaling one thread that another has finished work, and CSemaphore for limiting concurrent access to a resource pool. Rather than calling Lock/Unlock directly, the idiomatic pattern is to wrap a CSingleLock (or CMultiLock for waiting on several objects at once) around the sync object inside a scoped block, so the lock is released automatically via the destructor even if an exception unwinds the stack. A CCriticalSection is by far the cheapest of these because it never crosses into kernel mode unless there's actual contention, making it the default choice for protecting a shared STL container or CMap between a worker thread and the UI thread.

🏏

Cricket analogy: A CCriticalSection is like a single-entry gate to the pitch during a rain delay - only the grounds crew supervisor holds the key at a time - while a CSemaphore is like allowing exactly three physios onto the field simultaneously during a drinks break.

Talking Back to the UI Thread

Because window handles belong to the thread that created them, a worker thread must never call CWnd member functions like SetWindowText or Invalidate directly on a window owned by the main UI thread - doing so causes intermittent deadlocks or corrupted painting. The safe pattern is for the worker to call PostMessage (or the CWinThread-level PostThreadMessage for threads with no window) with a custom WM_APP+n message and the result data packed into wParam/lParam or a heap-allocated struct pointer, letting the UI thread's own message handler perform the actual window update on its own thread. Progress reporting from a long-running worker, such as a file-copy operation, typically follows exactly this pattern: the worker posts a WM_APP_PROGRESS message every few percent, and the main frame's handler updates a CProgressCtrl.

🏏

Cricket analogy: A worker thread posting progress messages to the UI thread is like the twelfth man radioing updates to the dressing room rather than walking onto the field himself to change the scoreboard, since only the official scorer is authorized to touch it.

cpp
// Worker thread function
UINT CopyFileThreadProc(LPVOID pParam)
{
    CMyDoc* pDoc = static_cast<CMyDoc*>(pParam);
    CSingleLock lock(&pDoc->m_csData, TRUE); // block until acquired

    for (int i = 0; i <= 100; i += 5)
    {
        Sleep(50); // simulate work
        // Notify UI thread; never touch its windows directly
        pDoc->GetMainFrame()->PostMessage(WM_APP_PROGRESS, i, 0);
    }
    lock.Unlock();
    return 0;
}

// Launching it from the UI thread
void CMyDoc::StartBackgroundCopy()
{
    CWinThread* pThread = AfxBeginThread(CopyFileThreadProc, this);
    // pThread->m_bAutoDelete stays TRUE; we don't keep the pointer around
}

// In the frame's message map:
// ON_MESSAGE(WM_APP_PROGRESS, &CMainFrame::OnCopyProgress)
LRESULT CMainFrame::OnCopyProgress(WPARAM wParam, LPARAM /*lParam*/)
{
    m_wndProgressBar.SetPos((int)wParam);
    return 0;
}

Never call UpdateData, Invalidate, or any other CWnd method on a dialog or control from a worker thread. Even though it may appear to work under light testing, it introduces a race between the worker's window-manager call and the UI thread's own message pump, which manifests as intermittent hangs or GetLastError ERROR_INVALID_WINDOW_HANDLE failures under real-world load.

CSingleLock's constructor accepts a bInitialLock parameter; passing TRUE acquires the lock immediately (blocking if necessary), which is the pattern used in almost all real MFC code rather than calling Lock() separately afterward.

  • AfxBeginThread with a controller function creates a worker thread (no message pump); passing a CRuntimeClass creates a UI thread with one.
  • m_bAutoDelete defaults to TRUE, so the CWinThread object self-destructs when the thread function returns unless you explicitly opt out before resuming.
  • Never call TerminateThread; signal cooperative shutdown with a flag or CEvent instead to avoid corrupting CRT and MFC internal state.
  • CCriticalSection, CMutex, CEvent, and CSemaphore all derive from CSyncObject and are typically wrapped with CSingleLock for RAII-style scoped locking.
  • CCriticalSection is the cheapest synchronization primitive for intra-process use; CMutex is needed only for cross-process synchronization.
  • A worker thread must never call CWnd methods on windows owned by another thread; use PostMessage/PostThreadMessage to hand data to the owning thread.
  • Progress reporting from background work is implemented with a custom WM_APP+n message posted periodically to the UI thread's handler.

Practice what you learned

Was this page helpful?

Topics covered

#MFCMicrosoftFoundationClassesStudyNotes#MicrosoftTechnologies#MultithreadingInMFC#Multithreading#MFC#Worker#Threads#StudyNotes#SkillVeris#ExamPrep