How to kill a thread in Haskell

One other thing to note is that GHC programs terminate when the main thread terminates. The liveness of child threads is unimportant. If you design your app such that you can always signal the main thread that it's time to terminate, it doesn't matter how blocked any child threads are.


To expand on my comment above, you can't interrupt blocking foreign calls. You can, however, use nonblocking IO. In the case of the Network package, this means recvLen for strings, and recvFrom for bytestrings. I assume you're always specifying the threaded runtime as well?


You can call the ExitProcess() API from any thread in your app and the whole process, threads and all, will be terminated. There are some gotchas with some DLL detaches that can cause an issue and a process cannot be terminated until all handles for it have been released, but ExitProcess() always works fine for me as a last resort.

ExitProcess() does not care what state your threads are in. The can be blocked on I/O or running on a different processor than the thread that calls ExitProcess() - it does not matter, the OS will stop them all.

Rgds, Martin


In Posix environments you can terminate the entire process with:

-- | @'exitImmediately' status@ calls @_exit@ to terminate the process
--   with the indicated exit @status@.
--   The operation never returns.
exitImmediately :: ExitCode -> IO ()

From the unix package. There may be a similar non-Posix feature under the Win32 package.

However, it is better to design your application such that your signalling mechanisms are respected, of course.