如何让程序自动管理线程
2010-08-15 20:46:26 来源:WEB开发网具体 实现
下面给出它的具体实现。
ThreadTask::ThreadTask()
{
m_bKeepGoing = TRUE;
//表示已运行
DWORD nThreadId = 0;
//创建管理线程
m_Handle = (HANDLE)::CreateThread(NULL,0,ThreadTaskpro,0,0,&nThreadId );
}
void ThreadTask::AddHandle( CONST HANDLE cHandle )
{
CHandle *pHandle = new CHandle;
pHandle- >m_ThreadHandle = cHandle;
m_ObList.AddTail( pHandle );
}
void ThreadTask::CloseThreadHandles()
{
if ( m_ObList.GetCount() )
{
POSITION pos1, pos2;
CHandle *pHandle = (CHandle *)NULL;
//(CHandle类 相当简单,只有一个成员函数m_ThreadHandle)
DWORD dwExitCode = 0L;
for( pos1=m_ObList.GetHeadPosition(); (pos2=pos1)! =POSITION(NULL); )
{
//历遍所有已有的线程 句柄
pHandle = DYNAMIC_DOWNCAST( CHandle, m_ObList.GetNext( pos1 ) );
//获得第pos1个handle
VERIFY( ::GetExitCodeThread( pHandle->m_ThreadHandle, &dwExitCode ) );
//获得线程pHandle的当前状态
if ( dwExitCode != STILL_ACTIVE )
//如果已 完成
{
//释放当前句柄
m_ObList.RemoveAt( pos2 );
VERIFY( ::CloseHandle( pHandle->m_ThreadHandle ) );
delete pHandle;
pHandle = (CHandle *)NULL;
}
}
}
}
ThreadTask::~ThreadTask()
{
}
ThreadTask & ThreadTask::GetThreadTask()
{
//返回静态ThreadTask对象, 以便ThreadManager类调用
static ThreadTask Taker;
return(Taker);
}
BOOL ThreadTask::IsValid()
{
//是否已运行
BOOL bValid_Status = FALSE;
if ( (this != NULL) && AfxIsValidAddress( this, sizeof( ThreadTask ) ) )
bValid_Status = TRUE;
return( bValid_Status );
}
更多精彩
赞助商链接