TerminateThread

The TerminateThread function terminates a thread. It is a relatively drastic way to stop a thread and should be used with caution.

Function Signature

BOOL TerminateThread( _In_ HANDLE hThread, _In_ DWORD dwExitCode );

Parameters

hThread [in]
A handle to the thread to be terminated. This handle must have the THREAD_TERMINATE access right.
dwExitCode [in]
The application exit status for the thread. Use the exit code conventions.

Return Value

If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The TerminateThread function is used to terminate a thread. It is important to understand the implications of terminating a thread abruptly. When a thread is terminated, the following occurs:

If the terminated thread was the primary thread of a process, all other threads in the process are terminated as well. The system does not perform any special cleanup for other threads. For this reason, TerminateThread should only be called when the calling application has no other way to stop the thread.

It is generally recommended to use other mechanisms for thread termination, such as signaling events or setting flags that the thread periodically checks to exit gracefully.

Security Warning: Calling TerminateThread can lead to an inconsistent state in the calling process. For example, if the terminated thread owns a critical section, the critical section will never be released, potentially causing the process to deadlock. A thread can also be terminated while it is in the middle of an atomic operation, leading to data corruption. Therefore, this function should be used with extreme caution.

Exit Codes

The dwExitCode parameter specifies the thread's exit status. Typically, an exit code of 0 indicates successful termination, while a non-zero value indicates an error. The value STILL_ACTIVE (defined as 259) indicates that the thread is still running.

See Also