(vc6)在程序中使用AfxBeginThread函数创建线程释放方法:
1.使用函数GetExitCodeThread与TerminateThread。
以下为csdn上的例子http://topic.youkuaiyun.com/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;
}