Cum verific daca un thread este activ?
Raspuns
O metoda des intalnita la un search pe net este folosind functia WinAPI GetExitCodeThread.
Daca aceasta intoarce valoarea STILL_ACTIVE, inseamna ca thread-ul este activ.
Exemplu
Code: Select all
DWORD CheckThreadIsActive(DWORD dwThreadID, BOOL& bIsActive)
{
bIsActive = FALSE;
HANDLE hThread = ::OpenThread(THREAD_QUERY_INFORMATION, FALSE, dwThreadID);
if(NULL == hThread)
return ::GetLastError();
DWORD dwExitCode = 0;
BOOL bRet = ::GetExitCodeThread(hThread, &dwExitCode);
::CloseHandle(hThread);
if(! bRet)
return ::GetLastError();
if(STILL_ACTIVE == dwExitCode)
bIsActive = TRUE;
return NO_ERROR;
}
Alta metoda mai sigura este apeland functia WaitForSingleObject careia ii pasam valoarea 0 (zero) pentru time-out. In acest caz, WaitForSingleObject intoarce imediat iar daca valoarea de return este WAIT_TIMEOUT, atunci threadul este activ.
Exemplu
Code: Select all
DWORD CheckThreadIsActive(DWORD dwThreadID, BOOL& bIsActive)
{
bIsActive = FALSE;
HANDLE hThread = ::OpenThread(SYNCHRONIZE, FALSE, dwThreadID);
if(NULL == hThread)
return ::GetLastError();
DWORD dwRet = ::WaitForSingleObject(hThread, 0);
::CloseHandle(hThread);
if(WAIT_FAILED == dwRet)
return ::GetLastError();
if(WAIT_TIMEOUT == dwRet)
bIsActive = TRUE;
return NO_ERROR;
}
Note
- Pentru GetExitCodeThread, handle-ul thread-ului trebuie sa aiba dreptul de acces THREAD_QUERY_INFORMATION.
- Pentru WaitForSingleObject, handle-ul thread-ului trebuie sa aiba dreptul de acces SYNCHRONIZE.
<< Back to Windows API Index