Skip to content

Use of unsafe TerminateThread() function on Windows #2

@Ext3h

Description

@Ext3h

JThread::Kill in the Windows version uses TerminateThread:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms686717(v=vs.85).aspx

From the Microsoft documentation:

TerminateThread is a dangerous function that should only be used in the most extreme cases. You should call TerminateThread only if you know exactly what the target thread is doing, and you control all of the code that the target thread could possibly be running at the time of the termination. For example, TerminateThread can result in the following problems:

  • If the target thread owns a critical section, the critical section will not be released.
  • If the target thread is allocating memory from the heap, the heap lock will not be released.
  • If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent.
  • If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL.

I can unfortunately confirm from practical experience that every single of these warnings is valid. The use of JThread::Kill under Windows is very likely to send the CRT (or in bad cases even the Windows kernel) into internal deadlocks of all sorts. This is non-deterministic and depends on what the thread was actually doing at the time of termination, where as performing any form of memory allocation / deallocation or invoking any function from the Windows API is usually enough to cause problems.

TerminateThread does not provide any of the guarantees pthread_cancel does, specifically performing a graceful termination, allowing the thread not to handle the termination signal at all if not desired, and alike.

Consequently this also causes stability issues in the Windows builds of other libraries which build on top of JThread and use JThread::Kill in case of hangs, such as JRTPLIB in the RTPPollThread class.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions