还没弄好?之前和你说过了,其实就是WaitForSingleObject和CEvent,对于MFC,使用Afx方式创建线程有系列的方法可用,只要你保存了这个指针或句柄。
给你找了一段例程序,这里包含了判断和外部结束的全部方法,你不一定要创建这个类,只要保留CWinThread指针即可。
class CScrCapThread : public CWinThread
{
CEvent m_eventKill;
CEvent m_eventDead;
static CEvent m_eventAnotherDead;
BOOL IsKilling();
BOOL IsDead();
void KillThread();
virtual void Delete();
}
CScrCapThread::CScrCapThread()
:m_eventKill(FALSE,TRUE)
,m_eventDead(FALSE,TRUE)
{
m_bAutoDelete=FALSE;
}
BOOL CScrCapThread::IsKilling()
{
return ::WaitForSingleObject(m_eventKill,0)==WAIT_OBJECT_0;
}
BOOL CScrCapThread::IsDead()
{
return ::WaitForSingleObject(m_eventDead,0)==WAIT_OBJECT_0;
}
void CScrCapThread::Delete()
{
// calling the base here won't do anything but it is a good habit
CWinThread::Delete();
// acknowledge receipt of kill notification
VERIFY(m_eventDead.SetEvent());
VERIFY(m_eventAnotherDead.SetEvent());
}
void CScrCapThread::KillThread()
{
// Note: this function is called in the context of other threads,
// not the thread itself.
// reset the m_hEventKill which signals the thread to shutdown
VERIFY(m_eventKill.SetEvent());
// allow thread to run at higher priority during kill process
SetThreadPriority(THREAD_PRIORITY_ABOVE_NORMAL);
WaitForSingleObject(m_eventDead, INFINITE);
WaitForSingleObject(m_hThread, INFINITE);
// now delete CWinThread object since no longer necessary
if(m_bAutoDelete)
delete this;
}
简单的办法:
设置一个两个线程都可以访问的变量 ,如volatile bool bRunFlag;
当子线程开始运行时,则设置bRunFlag = true;
则可以判断子线程是否在运行。
关闭子线程
bRunFlag = false ;
WaitForSingleObject(threadHandle,INFINITE);
close(threadHandle);