joe_pool_is
Contributor
I don't use threads very often, and probably because they can be such a pain.
In tutorials, I see this type of syntax for CreateThread:
1. Why was the handle closed as soon as the thread was started?
2. How do I tell when the thread is finished? My current understanding is that I have to poll GetExitCodeThread to determine if my thread is STILL_ACTIVE or if it has ended and returned its exit code. There should be a better way!
3. What if I wanted to kill this thread? Is this the way?
Thanks in advance!
In tutorials, I see this type of syntax for CreateThread:
Code:
HANDLE hThread;
hThread = CreateThread(NULL, 0, ThreadFn, (LPVOID)param, 0, &dwThreadID);
if (hThread)
{
CloseHandle(hThread);
}
2. How do I tell when the thread is finished? My current understanding is that I have to poll GetExitCodeThread to determine if my thread is STILL_ACTIVE or if it has ended and returned its exit code. There should be a better way!
Code:
if (hThread != NULL)
{
DWORD dwExit;
if (GetExitCodeThread(hThread, &dwExit))
{
if (dwExit == STILL_ACTIVE)
TerminateThread(hThread, dwExit);
}
else if (dwExit != 0) // where 0 = ThreadFn's return value
ExitThread(dwExit);
CloseHandle(hThread);
// above is where it seems like HANDLEs should be closed
}
3. What if I wanted to kill this thread? Is this the way?
Code:
PostThreadMessage(dwThreadID, WM_CLOSE, 0, 0);
Thanks in advance!