Kill a running thread

After creating this thread, I am immediately killing it before the thread completes its execution.

I assume you mean you are using TerminateThread() in the following fashion:

HANDLE thread = CreateThread(...);

// ...
// short pause or other action?
// ...

TerminateThread(thread, 0); // Dangerous source of errors!
CloseHandle(thread);

If that is the case, then no, the thread executing RecordThread() will be stopped exactly where it is at the time that the other thread calls TerminateThread(). As per the notes in the TerminateThread() documentation, this exact point is somewhat random and depends on complex timing issues which are out of your control. This implies that you can't handle proper cleanup inside a thread and thus, you should rarely, if ever, kill a thread.

The proper way to request the thread to finish is by using WaitForSingleObject() like so:

HANDLE thread = CreateThread(...);

// ...
// some other action?
// ...

// you can pass a short timeout instead and kill the thread if it hasn't
// completed when the timeout expires.
WaitForSingleObject(thread, INFINITE);
CloseHandle(thread);

http://msdn.microsoft.com/en-us/library/windows/desktop/ms682659%28v=vs.85%29.aspx

ExitThread is the preferred method of exiting a thread in C code. However, in C++ code, the thread is exited before any destructors can be called or any other automatic cleanup can be performed. Therefore, in C++ code, you should return from your thread function.

However the function calls will of course be completed because they're called before the ExitThread().


killing thread is the last resort - as Andre stated it leaves data in unknown state, you should never do that if thread works on shared object. Better choices are to notify thread to finish work by:

-using global volatile (important) variable which is changed only by main thread and tested by workers
-using signal type synchronization objects (mainly Events) also set by main thread and tested by workers