Asynchronous exceptions

throwTo is asynchronous

throwTo raises an exception in another thread, at a point the target does not choose. The exception belongs to the AsyncException type, and killThread is throwTo with ThreadKilled:

throwTo :: ThreadId -> SomeException -> IO () killThread :: ThreadId -> IO () mask :: ((forall a. IO a -> IO a) -> IO b) -> IO b

throwTo blocks until the target can receive the exception, so a thread in a masked section delays the throw. That is the mechanism a clean shutdown uses: mask the critical part, let the exception arrive at the boundary, clean up with finally.

A worker that is cancelled

module Main (main) where import Control.Concurrent (forkIO, newEmptyMVar, putMVar, takeMVar, threadDelay, throwTo) import Control.Exception (AsyncException (ThreadKilled), finally) main :: IO () main = do done <- newEmptyMVar tid <- forkIO $ (threadDelay 1000000 >> putStrLn "worker finished") `finally` (putStrLn "worker cleaned up" >> putMVar done ()) threadDelay 10000 throwTo tid ThreadKilled takeMVar done putStrLn "main saw the worker end"

ghc -Wall -O1 -threaded -o async async.hs
./async

worker cleaned up
main saw the worker end

finally and the cleanup

The worker sleeps for a second and the main thread kills it after ten milliseconds, so worker finished never prints. What does print is the finally action, which runs on the way out whether the body returned or raised: the cleanup runs, signals the main thread, and the program ends with the two lines above.

mask and the window

An asynchronous exception can arrive between two steps that must not be separated, such as taking a lock and recording that you took it. mask defers the exception for the duration of its block and lets it arrive in the interruptible operations, such as takeMVar and threadDelay:

mask $ \restore -> do takeMVar lock -- inside the mask: not interruptible here r <- restore (work) -- the window where a throw can land putMVar lock () pure r

restore is the argument of the function mask passes in: it puts the mask back to what it was, so the exception can arrive only where the code says it may. The functions of Control.Exception such as bracket are built with exactly this pattern, which is why using them is easier than writing a mask by hand.

A last rule: an asynchronous exception must not be caught and swallowed. A handler that catches SomeException and returns a value turns a cancelled thread into a thread that ignores its cancellation, and the shutdown that follows hangs. Catch the exception you mean, and let the others through.

Exercises

  1. Remove the finally and describe what is printed.
  2. Add a second worker and kill only one of them.
  3. Use bracket to open and close a handle in a thread.
  4. Explain why throwTo can block.
  5. Write a mask with a restore window and a throw that lands in it.
  6. Catch ThreadKilled, print a line and rethrow it, and explain the difference from swallowing it.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does throwTo tid ThreadKilled do?

    Answer

    Raises ThreadKilled in the target thread at a point it does not choose

    It is an asynchronous exception, delivered where the target can receive it.

  2. Why does worker finished not print?

    Answer

    The worker is killed during its delay, before the line

    The kill arrives after ten milliseconds and the sleep was a second.

  3. What does finally guarantee?

    Answer

    The cleanup runs whether the body returned or raised

    Both paths run the cleanup, which is why the MVar is filled.

  4. What does this program print? ``module Main (main) where import Control.Exception (finally) main :: IO () main = putStrLn "body" finally putStrLn "cleanup"``

    Answer

    body then cleanup

    The body runs and the cleanup follows it.

  5. What does mask do?

    Answer

    Defers asynchronous exceptions for the block and passes restore

    restore re-opens the window at the point the code chooses.

  6. What does this program print? module Main (main) where import Control.Exception (bracket) main :: IO () main = bracket (putStrLn "acquire") (\_ -> putStrLn "release") (\_ -> putStrLn "use")

    Answer

    acquire use release

    bracket acquires, uses and releases in that order.

  7. Why is throwTo able to block?

    Answer

    It waits until the target is at a point where it can receive the exception

    A masked section delays the delivery, so the caller waits.

  8. What does this program print? module Main (main) where import Control.Exception (try, SomeException, throwIO) main :: IO () main = do r <- try (throwIO (userError "x")) :: IO (Either SomeException ()) case r of Left _ -> putStrLn "caught" Right _ -> putStrLn "fine"

    Answer

    caught

    try turns the exception into a Left, and the case prints caught.

  9. Why is swallowing a ThreadKilled a bug?

    Answer

    The thread ignores its cancellation and the shutdown hangs

    Cancellation is delivered as an exception, and catching everything defeats it.

  10. What does this program print? ``module Main (main) where import Control.Exception (onException) main :: IO () main = putStrLn "ok" onException putStrLn "handler"``

    Answer

    ok

    The body succeeded, so the exception handler did not run.

The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev