返回> 网站首页
在主线程中终止带消息处理的线程的方法
yoours2011-03-21 16:29:21
简介一边听听音乐,一边写写文章。
当线程中有消息处理时,如一般的线程中显示操作结果时,此时如果要在主线程中使用WaitForSingleObject的话,往往会导致阻塞,例如如下的主线程终止副线程,而副线程中用了诸如SendMessage的函数,那么自然相互锁住了,因为你运行等待的函数没有返回,那么线程中的消息得不到处理,自然就两边的线程都阻塞在那里,此时可以使用API函数MsgWaitForMultipleObjects来解决,如下所示。将等待到的消息进行处理。再继续等待,直到超时或等待成功。
- // 停止线程, nTime为等待毫秒
- bool CThreadBase::StopThread( UINT nTime )
- {
- if( NULL == m_pWinThread )
- return false;
- m_bIsRunning = false;
- DWORD result;
- MSG msg;
- HANDLE hHandle = m_pWinThread->m_hThread;
- while( true )
- {
- result = MsgWaitForMultipleObjects( 1, &hHandle, FALSE, nTime, QS_ALLINPUT );
- if( result == WAIT_TIMEOUT )
- {
- return false;
- }
- else if ( result == ( WAIT_OBJECT_0 ) )
- {
- return true;
- }
- else
- {
- PeekMessage( &msg, NULL, 0, 0, PM_REMOVE );
- DispatchMessage( &msg );
- continue;
- }
- }
- return true;
- }
文章评论
1385人参与,0条评论