Typically, this (calling TerminateThread) is bad because the thread may allocate some resources (i.e. file descriptors) that will not be available until the whole process is complete. Moreover, CloseHandle does not stop the thread.
If you have a long operation inside your thread, then at least use
while(!ShouldExit) { DoOneMoreIteration(); }
cycle. That way, you can terminate the stream by setting IfExit to 1 (or "true" if it is a C ++ and bool variable) and calling WaitForSingleObject in this stream descriptor to make sure it is complete.
For the comment, eran: ShouldExit should be declared as "volatile".
If you expect input (the console, I suppose), you can use non-blocking ("overlapping") I / O with standard input.
For example, see this question: Checking Win32 File Streams for Available Input
It will 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 do something better (avoid processor overflows), use WaitForMultipleObjects and go beyond 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);