Hacker News new | ask | show | jobs
by int_19h 239 days ago
> Do you mean that there is no valid use-case where you wish to interrupt a blocking thread due to I/O, for example?

This is certainly a common case, but killing a thread with a blocking native call on it is a very poor way to do so (not the least because you don't know what locks it might be holding at the moment it gets killed - imagine what happens if that's one of the locks used by low-level heap, for example). The proper way to address it is to use asynchronous I/O APIs that allow for cooperative cancellation. Unfortunately Linux doesn't exactly have a good track record in that department, which is why people do these kinds of hacks. On Windows you get stuff like https://learn.microsoft.com/en-us/windows/win32/fileio/cance....

1 comments

I shouldn't have used the word "kill" in the context of talking about threads, that seems to have created some misunderstandings.

>The proper way to address it is to use asynchronous I/O APIs that allow for cooperative cancellation.

I completely agree here. Async is the go-to for IO-bound operations and the ability to cancel (sends an exception to the task) is a very useful feature.

Killing threads, as in non-gracefully stopping them is a bad idea regardless of language, and not something I would encourage nor something I do myself.

In Python, if there is CPU-bound long-running routine that need to be executed concurrently, then this can be done using multiprocessing. I'd say, if external resource usage is well-defined then a good way to stop such a task would be to send a sigterm, wait, then send a signal 9 if it hasn't stopped after a grace period. If needed, perform a cleanup afterwards.

The problem with python and threads in my experience is that even a graceful interruption of individual threads can be tedious to get right.

Thanks for the link btw.