What happens if we forcefully kill a running thread
I have a thread namely RecordThread() which calls some complex and time consuming functions. In these functions I am using try-catch blocks, allocating and deallocation memory and using critical section variables etc.
like
void RecordThread()
{
AddRecord();
FindRecord();
DeleteRecord();
// ...
ExitThread(0);
}
After creating this thread, I am immediately killing it before the thread completes its execution. In this case what happens if the thread is forcefully killed? Do the internal functions (AddRecord, DeleteRecord) complete their execution after we killed the thread?
I assume you mean you are using
TerminateThread()in the following fashion: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 callsTerminateThread(). As per the notes in theTerminateThread()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: