TerminateThread function

The TerminateThread function terminates a thread and removes it from the thread list of a specified process.

BOOL TerminateThread(
  HANDLE hThread,
  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-defined exit code for the thread. Use the macro ExitThread to set the exit code.

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

This function is used to forcibly terminate a thread. It should be used with caution, as it can lead to undesirable side effects, such as:

  • Memory leaks: The terminated thread's allocated memory may not be freed.
  • Resource leaks: Any handles or other resources held by the thread may not be released.
  • Data corruption: If the thread was in the middle of modifying shared data, the data may be left in an inconsistent state.
  • Deadlocks: Other threads in the process may be waiting for resources that were held by the terminated thread.

In most cases, it is preferable to use a signaling mechanism (such as events or mutexes) to request a thread to terminate gracefully. This allows the thread to clean up its resources before exiting.

If the thread is terminated, its exit status is set to dwExitCode. All open handles to the thread are invalid. The system frees the thread's resources, such as its stack and its thread environment block (TEB).

See also