主线程用afxBeginThread()创建多个线程安全退出的办法
HANDLE hand[2]; CCriticalSection m_crisecoin; CEvent m_event; struct Student { int nNO; int nYear; CWnd *wnd; BOOL bExit; }; Student stdent; //创建线程 void CMyDlg::OnBnClickedButtonBegin() { stdent.nNO = 1; stdent.nYear = 10000; stdent.wnd = this; stdent.bExit = FALSE; pThread[0] = AfxBeginThread( threadADD , &stdent ); pThread[1] = AfxBeginThread( threadADD1 , &stdent ); hand[0] = CreateEvent( NULL,FALSE,FALSE , NULL );//这个是事项 hand[1] = CreateEvent( NULL,FALSE,FALSE , NULL ); } //线程里面的程序 UINT threadADD( LPVOID p ) { Student *pStudent = ( Student *)p; for ( int i = 0; i < 9999999; i++ ) { if ( pStudent->bExit ) { SetEvent(hand[0]); return 0; } ::SendMessage( pStudent->wnd->GetSafeHwnd() , WM_USER_ADD , pStudent->nNO++, 0 ); Sleep(500); } return 0; } UINT threadADD1( LPVOID p ) { Student *pStudent = ( Student *)p; for ( int i = 0; i<1000000; i++ ) { if ( pStudent->bExit ) { SetEvent( hand[1]); return 0; } ::SendMessage( pStudent->wnd->GetSafeHwnd() , WM_USER_ADD1 , (pStudent->nYear)--,0); Sleep( 500 ); } return 0; } 退出程序: BOOL CMyDlg::ExistThread() { m_crisecoin.Lock(); stdent.bExit = TRUE; m_crisecoin.Unlock(); DWORD dwWait =0; dwWait = ::WaitForMultipleObjects( 2, hand , TRUE,INFINITE); return TRUE; } //挂起线程; void CMyDlg::OnBnClickedButtonSuperthread() { SuspendThread( pThread[0]->m_hThread ); SuspendThread( pThread[1]->m_hThread ); } //唤起线程 void CMyDlg::OnBnClickedButtonResunme() { ResumeThread( pThread[0]->m_hThread ); ResumeThread( pThread[1]->m_hThread ); }