bool ThreadClass::StopAll(void)
{
std::deque<DWORD> dqThreads;
HANDLE hThreadSnap = NULL;
BOOL bRet = FALSE;
THREAD_INFORMATION_EX tie;
DWORD dwThisThread = ::GetCurrentThreadId(); // used for not killing ourself
// Take a snapshot of all threads currently in the system.
DWORD dwProcessID=GetCurrentProcessId();
hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, dwProcessID);
if (hThreadSnap == INVALID_HANDLE_VALUE)
return false;
// Fill in the size of the structure before using it.
tie.te32.dwSize = sizeof(THREADENTRY32);
// Walk the thread snapshot to find all threads of the process.
// If the thread belongs to the process, add its information
// to the display list.
if (Thread32First(hThreadSnap, &tie.te32))
{
do
{
if (tie.te32.th32OwnerProcessID == dwProcessID)
{
dqThreads.push_back(tie.te32.th32ThreadID);
ZeroMemory(&tie, sizeof(THREAD_INFORMATION_EX));
tie.te32.dwSize = sizeof(THREADENTRY32);
}
}
while (Thread32Next(hThreadSnap, &tie.te32));
bRet = TRUE;
}
//else
// return false; // could not walk the list of threads
CloseHandle (hThreadSnap);
//
HANDLE ThreadArray[64];
int ThreadCount = 0;
m_cs.Lock();
std::map<DWORD, ThreadClass*>::iterator it=m_mapThreads.begin();
for(;it!=m_mapThreads.end();it++)
{
if( std::find(dqThreads.begin(),dqThreads.end(),it->first)==dqThreads.end())
{
//the thread not found
m_mapThreads.erase(it,it);
}
else
{
try
{
it->second->SetStopFlag();
if(ThreadCount<64)
ThreadArray[ThreadCount++] = it->second->m_hThread;
}
catch(...)
{
}
}
}
m_cs.Unlock();
DWORD dwRet=WaitForMultipleObjects(ThreadCount,ThreadArray, TRUE, 5000);
switch(dwRet) {
case WAIT_OBJECT_0:
g_Log.Debug("%s[%d]WaitForMultipleObjects return WAIT_OBJECT_0",__FUNCTION__,__LINE__);
break;
case WAIT_ABANDONED_0:
g_Log.Debug("%s[%d]WaitForMultipleObjects return WAIT_ABANDONED_0",__FUNCTION__,__LINE__);
break;
case WAIT_TIMEOUT:
g_Log.Debug("%s[%d]WaitForMultipleObjects return WAIT_TIMEOUT",__FUNCTION__,__LINE__);
break;
default:
g_Log.Debug("%s[%d]WaitForMultipleObjects return %08x",__FUNCTION__,__LINE__,dwRet);
break;
}
return true;
}