Simple Multithreading in C++ / MFC

Right now I am just starting with a very simple example – no fancy stuff – just a single thread to demonstrate a sequence that updates a counter 20 times per second.

//---- First example: Using global vars and fn
int gnCurValue;
int gnMaxValue;
BOOL gfStopNow;

UINT MyThreadProc( LPVOID pParam )
{
    while ( !gfStopNow && (gnCurValue < gnMaxValue) ) {
        gnCurValue++;
        Sleep( 50 ); // would do some work here
    }
    return(1);
}

void CThreadDlg::OnBnClickedStart()
{
    gnCurValue= 0;
    gnMaxValue= 5000;
    gfStopNow= 0;
    m_ctlStatus.SetWindowText("Starting...");
    SetTimer( 1234, 333, 0 ); // 3 times per second

    AfxBeginThread( MyThreadProc, 0 ); // <<== START THE THREAD
}

void CThreadDlg::OnBnClickedStop()
{
    gfStopNow= TRUE;
    KillTimer( 1234 );
    m_ctlStatus.SetWindowText( "STOPPED" );
}

void CThreadDlg::OnTimer(UINT_PTR nIDEvent)
{
    CString sStatusMsg;
    sStatusMsg.Format("Running: %d", gnCurValue );
    m_ctlStatus.SetWindowText( sStatusMsg );

    CDialog::OnTimer(nIDEvent);
}

Sample Visual Studio 2003 code here: Thread.zip

Leave a Reply