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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | //---- 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