关于中断线程问题

 (vc6)在程序中使用AfxBeginThread函数创建线程释放方法:

1.使用函数GetExitCodeThread与TerminateThread。

 以下为csdn上的例子http://topic.csdn.net/t/20031219/12/2581021.html

 首先声明一个全局变量:  
  extern   CWinThread   *pThread;//在.h中  
   
  然后定义:CWinThread   *pThread=NULL;//.cpp中  
   
  在你的线程类的BOOL   CMyThread::InitInstance()里加入:  
   
  pThread=AfxGetThread();  
   
  最后,在你要结束的地方加入:  
   
  if(pThread)  
  {   
      DWORD   exit;   
      GetExitCodeThread(pThread->m_hThread,&exit);   
      TerminateThread(pThread->m_hThread,exit);  
  }  
   
  这样就结束了

  值得说明的是:线程外部终止线程应该是::TerminateThread吧,AfxEndThread应该和::_endthread一样在线程内终止线程,线程的自然结束是最好的,否则不小心会内存泄露的

2.使用事件 http://www.itzhe.cn/Programme/HTML/36801_2.html#

 可以从外部用事件通知来优雅地结束线程
启动线程
m_pThreadWrite=AfxBeginThread(ThreadProc,(LPVOID)this);
线程体。为了避免在静态函数中引用对象指针的麻烦,调用对象参数的线程体成员函数。
UINT CMyClass::ThreadProc(LPVOID lp)
{
CMicrophoneInput* pInput=(CMicrophoneInput*)lp;
return pInput->Run();
}
简单的循环检测退出标志
UINT CMyClass::Run()
{
HRESULT hr;
if(!InitInstance()){
TRACE("InitInstance failed/r/n";
return ExitInstance();
}
while(!IsKilling()){
//do something
}
return ExitInstance();
}
重设退出标志
BOOL CMyClass::InitInstance()
{
m_eventKill.ResetEvent();
m_eventDead.ResetEvent();
//do something
return TRUE
}
设已退出标志
UINT CMyClass::ExitInstance()
{
//do something
m_eventDead.SetEvent();
return 0;
}
检查退出标志
BOOL CMyClass::IsDead()
{
return WaitForSingleObject(m_eventDead,0)==WAIT_OBJECT_0;
}
BOOL CMyClass::IsKilling()
{
return WaitForSingleObject(m_eventKill,0)==WAIT_OBJECT_0;
}
在外部可以这样终止线程
//check if dead
if(!IsDead()&&m_pThreadWrite!=NULL){
m_eventKill.SetEvent();
WaitForSingleObject(m_eventDead,INFINITE);
m_pThreadWrite=NULL;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值