Using 4016017 threads and asynchronous exceptions to solve ADC1.1

Dec 3, 2026

A cursed solution to Advent of Code 1.1 which yields surprisingly good insights about Haskell asynchronous exceptions and (uninterruptible) masking

Once in a while I feel like doing something silly.

So… here’s a solution to the first and easiest Advent of Code challenge using O(n2)O(n^2) threads and asynchronous exceptions, uninterruptible masking, and even IO-fixpoints.

Beware! The Haskell in this post is not for the faint of heart.

1 The obvious solution

To get the problem statement out of the way, here’s my one-liner solution:

import Data.List
main = print . product . map (read . head) . take 3 . reverse
             . sortOn length . group . sort . lines =<< readFile "i"

The input is given in a file called i, and it’s just a list of numbers like:

100
222
300
222
400

In this list, the number occurring more often is 222, which occurs twice. The problem is simply to take the three numbers occurring more often and taking their product. The “official” input has 2004 lines.

This solution should be easy to read, even for non-Haskellers. Just read it right to left, starting with readFile (because f . g stands for function composition, “f after g”).

2 Let’s get crazy

Now, let’s try to do the same thing, but as cursed as possible. Can we write this program without group-ing and sort-ing entirely, nor using maps or other Ord-ered data structures at all? And it must be wicked.

I had a few good laughs to finally end up with the following monstrosity. It will work roughly like this:

  1. Spawn a thread off of main for every number in the input (for a total of 2004 workers).
Fig 1. Spawn
  1. Throw an asynchronous exception from each thread to all the others announcing each thread’s thread-id and input number.

    Asynchronous exceptions1 are essentially a Haskell-only feature that allows a thread to throw exceptions to another thread. This allows us to define combinators like timeout at the library level as well as create our own composable concurrency abstractions like async. Or, you know, to implement a full-blown Erlang-style actor framework2. Your mileage may vary.

Fig 2. Throw
  1. Catch all exceptions thrown to each thread and accumulate a list of the threads which have the same number as you.
Fig 3. Accumulate
  1. For all threads with the same number, elect a leader, and the leader throws to the main thread its number after sleeping an amount proportional to the occurrences.
Fig 4. Elect
  1. The main thread catches each number thrown to it and prepends to a list. The last three numbers to arrive will be at the head of the list and will be the three with most occurrences (the leader of the number with more occurrences will have slept for more time, and thus sent its number later: the infamous sleep sort)
Fig 5. Collect

3 The devil is in the deadlocks

How do we implement this? It takes just about 30 Haskell lines! (And a lot of care to not deadlock the heck out of them). Let’s start with the exception type we’ll throw to other threads:

data N = N ThreadId Int
  deriving (Show, Exception)

An N thread_id 333 is an exception capturing the id of the thread throwing that exception and the number assigned to that thread.

The main thread reads the input as lines and creates an IO reference to accumulate the results as the workers throw them to us. Then, it spawns one thread per input number and sets up one catch frame per worker. At the end, it takes the 3 most-recent (thus most-occurring) numbers and multiplies them (product):

main = do
  numbers <- lines <$> readFile "i"
  results <- newIORef []

  mid <- myThreadId

  uninterruptibleMask $ \unmask -> mdo
    ts <- mapM (\t -> forkIOWithUnmask (worker mid ts t)) numbers
    catchN (\(N _ m) -> modifyIORef results (m:)) unmask ts

  print . product . take 3 =<< readIORef results

The lines which are interesting to unpack capture the do-not-use-this-in-production-ever idiom beautifully:

  uninterruptibleMask $ \unmask -> mdo
    ts <- mapM (\t -> forkIOWithUnmask (worker mid ts t)) numbers
    catchN (\(N _ m) -> modifyIORef results (m:)) unmask ts
  1. The veil of uninterruptibleMask means we are unkillable3. Anyone trying to throw us an exception will block waiting to throw, and we won’t receive any of them! Even a ^C won’t interrupt us for now. The unmask function brought into scope allows us to go back to full-exception-receiving mode.

  2. We forkIOWithUnmask one thread per number. This spawns a thread with a worker that receives the number (t), the main thread id (mid), the worker ids (ts) and an unmask action.

  3. Now, all workers have been spawned, and we will block waiting to catch NN exceptions, one per worker. Every time we’re ready to receive the next exception, we’ll call unmask (inside catchN).

    The (\(N _ m) -> modifyIORef results (m:)) is the handler run when an N tid m exception is thrown to main. It simply accumulates the thrown number m in the results list stored in the IO reference.

  4. Did you notice the list of thread-ids constructed from spawning all the workers (ts) is fed as an input to each worker itself? Such is the dark magic of RecursiveDo.

The worker will use a pattern similar to main. It receives the main thread id (sink), the thread id of all workers (ws), the number (n), and the action to unmask exceptions (unmask). It creates an IO reference to accumulate a list of the thread ids of all other workers that have the same number as itself. It’s split across the next three code blocks:

worker sink ws (read -> n) (unmask :: forall a. IO a -> IO a) = do
  me    <- myThreadId
  group <- newIORef []
  -- ...

The worker throws to all other workers its number, then catches the numbers all other workers send it. The forked worker inherits the uninterruptibleMask state of the parent thread, and unmask was received as an argument:

  -- ...
  mapM (\w -> forkIO (throwTo w (N me n))) ws {- forkIO: don't deadlock -}
  catchN (\(N f m) -> when (m == n) (modifyIORef group (f:))) unmask ws
  -- ...

Two noteworthy things:

Each worker will determine whether they are a leader (the thread responsible for communicating the number shared by a group of threads to main), or not a leader. Each worker determines this independently by comparing its thread id against its friends. The thread with the highest ThreadId is the leader of that group:

  -- ...
  friends <- filter (/= me) <$> readIORef group

  let leader = all (\f -> fromThreadId f < fromThreadId me) friends
  when leader $ do
    mapM (\_ -> throwTo sink (N me 0)) friends
    threadDelay ((length friends + 1)*1_000_000)
    throwTo sink (N me n)

The leader throws immediately one zero-d exception per friend in the group because main is expecting one exception per worker. Secondly, it sleeps an amount of time proportional to the amount of friends (aka the amount of occurrences of that number). This means a number with more occurrences will be delivered later to main. Only afterwards, it throws its number to main. The last thrown number is the one with most occurrences!

Finally, we have catchN, which just waits forever unmasked (unmask wait) NN times, until an exception is thrown NN times (if we hadn’t unmasked the wait, no exception would ever arrive). Every time the exception arrives, it aborts the wait, and runs the catch handler. On the last catch, we stop waiting (this is when i > 0).

catchN handler unmask = foldr c (unmask wait) . zipWith const [0..]
  where
    wait = forever (threadDelay maxBound)
    c i a = a `catch` \e -> do
                 handler e
                 when (i > 0) (unmask wait)

4 Conclusion

It was a fun challenge to solve the puzzle in this contrived way. Writing the solution was quite hard, since asynchronous exceptions are subtle. I ran into two major deadlocks while implementing this:

  1. The first was forgetting that throwTo blocks until the exception can be delivered to the thread. Since every worker is uninterruptibly masked, throwing to them would block inside the uninterruptible mask.

    The solution is to forkIO a thread to do the throwTo. That forked thread will be blocked, but the worker will move on. When it is done, it will unmask, and all the threads waiting to deliver exceptions will start to succeed.

  2. My second mistake was forgetting that a forked thread inherits the masked state of its parent. So, the forkIO being under main’s uninterruptibleMask means every worker is already uninterruptibly masked.

    Not accounting for this, I had a second uninterruptibleMask in the worker, and then its corresponding unmask was only unmasking the innermost mask. The worker would still be masked because of the inherited mask when I was expecting it to be unmasked, and you can imagine the rest.

Anyway, here’s the full code:

{-# LANGUAGE RecursiveDo, ViewPatterns, DeriveAnyClass #-}
import Data.IORef
import Control.Monad
import Control.Concurrent
import Control.Exception
import GHC.Conc.Sync

data N = N ThreadId Int
  deriving (Show, Exception)

catchN handler unmask = foldr c (unmask wait) . zipWith const [0..]
  where
    wait = forever (threadDelay maxBound)
    c i a = a `catch` \e -> do
                 handler e
                 when (i > 0) (unmask wait)

-- uninterruptible masking state is inherited from main
worker sink ws (read -> n) (unmask :: forall a. IO a -> IO a) = do
  me    <- myThreadId
  group <- newIORef []

  mapM (\w -> forkIO (throwTo w (N me n))) ws {- forkIO: don't deadlock -}
  catchN (\(N f m) -> when (m == n) (modifyIORef group (f:))) unmask ws

  friends <- filter (/= me) <$> readIORef group

  let leader = all (\f -> fromThreadId f < fromThreadId me) friends
  when leader $ do
    mapM (\_ -> throwTo sink (N me 0)) friends
    threadDelay ((length friends + 1)*1_000_000)
    throwTo sink (N me n)

main = do
  numbers <- lines <$> readFile "i"
  results <- newIORef []

  mid <- myThreadId

  uninterruptibleMask $ \unmask -> mdo
    ts <- mapM (\t -> forkIOWithUnmask (worker mid ts t)) numbers
    catchN (\(N _ m) -> modifyIORef results (m:)) unmask ts

  print . product . take 3 =<< readIORef results

Note: this, and all the code, was written fully by me, human.


  1. “Asynchronous Exceptions in Haskell” by The Simons et. all↩︎

  2. “An Exceptional Actor System (Functional Pearl)” by Patrick and Lindsey↩︎

  3. Please, please, do not use uninterruptibleMask gratuitously. You almost, almost, always want interruptible operations to be interruptible, even when masked. See The Haskell Unfolder Episode 15: interruptible operations for an in-depth explanation.↩︎