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. [code language="cpp"] //---- 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); } [/code] Sample Visual Studio 2003 code here: Thread.zip

Comments

Popular posts from this blog

Using the Supervisor Controller Pattern to access View controls in MVVM

Getting started with Tesseract optical character recognition (OCR) library in Visual Studio

How to send an e-mail via Google SMTP using C#