On Jun 19, 2019, at 22:14, Matúš Valo firstname.lastname@example.org wrote:
Currently it is not possible to "kill" thread which is blocked. The rationale for this is handling situations when thread is blocked - e.g. when thread is quering DB when lock occurred on Database.
pthread library and Windows API contains mechanisms for forced termination of threads - see  and .
The Windows function starts off its description with “TerminateThread is a dangerous function that should only be used in the most extreme cases.”
The POSIX function may or may not be safer. By default it is—but only because by default it doesn’t actually terminate the thread, it just sends a signal which sets a flag to be checked at the next cancel point. If the blocked operation can’t be interrupted by the signal, it stays blocked. If it can be interrupted, then you could have just signaled it instead, which is safer and easier to manage, especially from Python.
Either way, there’s no way to safely clean up after it. (Deleting the threading library’s own reference to its Thread object doesn’t solve that.)
And if your program regularly needs to terminate threads, your program almost certainly needs to be redesigned.
What you almost always want is signals, asyncio (a lot more operations can be canceled, and it’s usually less bad when then can’t), or something specific to your operation (e.g., a database library might have a connection-closing method, or maybe you can just close a file handle). The advantage to these solutions is that they generally mean the blocking operation exits immediately by raising an exception, which the thread can handle Pythonically to make sure everything ends up in the right state (usually just letting the exception propagate up to the top-level thread function and exit normally is all you need).
When you really do need to occasionally terminate something blocking, put it in a process rather than a thread. Processes can be killed, the OS automatically cleans up everything except persistent objects, and there’s no state being shared with your main process that could be corrupted. You can still have problems (e.g., if you’re using lockfiles manually, and you hard-kill a process that’s created the lockfile, it’s left behind), but with processes things are safe except in special conditions, as opposed to threads where things are broken except in special conditions.