On Thu, 20 Jun 2019 at 06:15, Matúš Valo <matusvalo@gmail.com> wrote:
Hi All,

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. In this case, the main thread has no way how to stop the blocked thread. Killing a thread is also popular question - see [1][2].

pthread library and Windows API contains mechanisms for forced termination of threads - see [3] and [4]. It is also simple to use them using ctypes library but after this action one need to "clean" internal data structures which is bad practice:

import time
import threading
import ctypes

def handler():
    # blocked thread handler

t = threading.Thread(name='bar', target=handler)
libpt = ctypes.cdll.LoadLibrary("libpthread.so.0")

# This is nasty cleaning of internal python structures
del threading._active[t.ident]

Is if feasible to add canceling threads to python threading library? I am willing to help creating a patch (at least for linux).

Back in the day we used the .NET API for king threads from IronPython. It made threads so much saner to work with. It's been an egregious lack in the Python thread API for years and every time it's brought up people rush to say you shouldn't do it as what you really want to do is something else. 


[1] https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread
[2] https://www.geeksforgeeks.org/python-different-ways-to-kill-a-thread/
[3] http://man7.org/linux/man-pages/man3/pthread_cancel.3.html
[4] https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-terminatethread
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-leave@python.org
Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/ZDERRWIBX7JP5F2VRTTGD4OMCUSMH3QB/
Code of Conduct: http://python.org/psf/codeofconduct/
Michael Foord
Python Consultant, Contractor and Trainer