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.
- finally body cleanup runs the cleanup in both cases, which is the tool for releasing a resource.
- bracket acquire release use is the same with the acquisition inside, and it is the shape to use for a file or a lock.
- onException runs the handler only on an exception, for the case where the success path does its own cleanup.
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
- Remove the finally and describe what is printed.
- Add a second worker and kill only one of them.
- Use bracket to open and close a handle in a thread.
- Explain why throwTo can block.
- Write a mask with a restore window and a throw that lands in it.
- 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.
-
What does
throwTo tid ThreadKilleddo?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.
-
Why does
worker finishednot print?Answer
The worker is killed during its delay, before the line
The kill arrives after ten milliseconds and the sleep was a second.
-
What does
finallyguarantee?Answer
The cleanup runs whether the body returned or raised
Both paths run the cleanup, which is why the MVar is filled.
-
What does this program print? ``
module Main (main) where import Control.Exception (finally) main :: IO () main = putStrLn "body"finallyputStrLn "cleanup"``Answer
body then cleanup
The body runs and the cleanup follows it.
-
What does
maskdo?Answer
Defers asynchronous exceptions for the block and passes restore
restore re-opens the window at the point the code chooses.
-
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.
-
Why is
throwToable 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.
-
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.
-
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.
-
What does this program print? ``
module Main (main) where import Control.Exception (onException) main :: IO () main = putStrLn "ok"onExceptionputStrLn "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