Generally this (calling TerminateThread) is a bad thing to do because a thread may allocate some resources (i.e., file descriptors) which will be unavailable until the whole process terminate. Even more, the CloseHandle does not stop the thread.
If you have some lengthy operation inside your thread, then at least use the
while(!ShouldExit)
{
DoOneMoreIteration();
}
cycle. This way you can terminate the thread by setting ShouldExit to 1 (or 'true', if it is C++ and bool variable) and the call WaitForSingleObject on this thread's handle to ensure it has finished.
For eran's comment: The ShouldExit must be declared as 'volatile'.
If you're waiting for some input (a console I suppose), then you might use the non-blocking ("overlapped") I/O with standard input.
E.g., see this question: Checking Win32 file streams for available input
It would be something like
HANDLE h = GetStdHandle(STD_INPUT_HANDLE);
while(!ShouldExit) {
if(WaitForSingleObject(h, FALSE, SomeTimeoutValue) == WAIT_OBJECT_0)
{
... use std::cin - it has some input and won't block
}
}
To make things better (avoid CPU overburn) use WaitForMultipleObjects and break outside the loop on some external event.
/// Global var
HANDLE SomeGlobalEvent;
/// ThreadProc():
HANDLE h[2];
h[0] = GetStdHandle(STD_INPUT_HANDLE);
h[1] = SomeGlobalEvent;
while(true) {
DWORD which = WaitForMultipleObjects(2, h, FALSE, SomeTimeoutValue);
if(which == WAIT_OBJECT_0)
{
... use std::cin - it has some input and won't block
} else
if(which == WAIT_OBJECT_1)
{
// got the termination event
break;
}
}
/// "Main" thread:
SomeGlobalEvent = CreateEvent(NULL, false, false, NULL);
HANDLE hThread = _beginthread(ThreadProc, 4096, NULL);
....
/// send termination signal
SetEvent(SomeGlobalEvent);
/// Wait for thread completion
WaitForSingleObject(hThread);