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 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
400In 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:
- Spawn a thread off of main for every number in the input (for a total of 2004 workers).
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
timeoutat the library level as well as create our own composable concurrency abstractions likeasync. Or, you know, to implement a full-blown Erlang-style actor framework2. Your mileage may vary.
- Catch all exceptions thrown to each thread and accumulate a list of the threads which have the same number as you.
- 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.
- 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)
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 resultsThe 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 tsThe veil of
uninterruptibleMaskmeans 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^Cwon’t interrupt us for now. Theunmaskfunction brought into scope allows us to go back to full-exception-receiving mode.We
forkIOWithUnmaskone 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 anunmaskaction.Now, all workers have been spawned, and we will block waiting to catch exceptions, one per worker. Every time we’re ready to receive the next exception, we’ll call
unmask(insidecatchN).The
(\(N _ m) -> modifyIORef results (m:))is the handler run when anN tid mexception is thrown to main. It simply accumulates the thrown numbermin the results list stored in the IO reference.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:
We must
forkIOa thread tothrowTo, becausethrowToblocks waiting for the exception to be delivered, but no worker can receive an exception until it unmasks (which only happens after the worker throws its number to all other threads). I expand on this deadlock in the conclusion. That’s 2004 new threads per each of the 2004 workers :).For each exception caught, we receive the thread id of the worker who sent it (
f) and that worker’s number (m). If we have the same number, we addfto our list of workers with the same numbers. We’ll call them our friends.
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)
times, until an exception is thrown 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:
The first was forgetting that
throwToblocks 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
forkIOa thread to do thethrowTo. 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.My second mistake was forgetting that a forked thread inherits the masked state of its parent. So, the
forkIObeing under main’suninterruptibleMaskmeans every worker is already uninterruptibly masked.Not accounting for this, I had a second
uninterruptibleMaskin the worker, and then its correspondingunmaskwas 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 resultsNote: this, and all the code, was written fully by me, human.
“Asynchronous Exceptions in Haskell” by The Simons et. all↩︎
“An Exceptional Actor System (Functional Pearl)” by Patrick and Lindsey↩︎
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.↩︎