Capstone C: the workers
The workers
Three threads take jobs from the queue until it is empty, and each one increments a counter before it returns. The main thread waits for the counter to reach three, which is the shutdown of the pool lesson, and then prints the results sorted by id.
A worker wraps its computation in try and evaluate: a job that throws becomes a result of -1 instead of killing the thread. That is the difference between a pool that reports a failure and one that silently loses a job.
outcome <- try (evaluate (runJob job)) :: IO (Either SomeException Int)
let value = fromRight (-1) outcome
The program
module Main (main) where
import Control.Concurrent (forkIO)
import Control.Concurrent.STM
import Control.Exception (SomeException, evaluate, try)
import Control.Monad (replicateM_, when)
import Data.Either (fromRight)
import Data.List (sortOn)
data Job = Job
{ jobId :: Int
, jobCost :: Int
}
data Result = Result
{ resultId :: Int
, resultValue :: Int
}
deriving (Show)
readJob :: TVar [Job] -> STM (Maybe Job)
readJob queue = do
jobs <- readTVar queue
case jobs of
[] -> pure Nothing
job : rest -> writeTVar queue rest >> pure (Just job)
runJob :: Job -> Int
runJob job
| jobCost job < 0 = error "negative cost"
| otherwise = jobCost job * 2
worker :: TVar [Job] -> TVar [Result] -> TVar Int -> IO ()
worker queue results finished = loop
where
loop = do
next <- atomically (readJob queue)
case next of
Nothing -> atomically (modifyTVar' finished (+ 1))
Just job -> do
outcome <- try (evaluate (runJob job)) :: IO (Either SomeException Int)
let value = fromRight (-1) outcome
atomically (modifyTVar' results (Result (jobId job) value :))
loop
main :: IO ()
main = do
queue <- newTVarIO [Job 1 5, Job 2 (-3), Job 3 7]
results <- newTVarIO []
finished <- newTVarIO 0
replicateM_ 3 (forkIO (worker queue results finished))
atomically $ do
done <- readTVar finished
when (done < 3) retry
values <- readTVarIO results
mapM_ print (sortOn resultId values)
ghc -Wall -O1 -threaded -o workers workers.hs
./workers
Result {resultId = 1, resultValue = 10}
Result {resultId = 2, resultValue = -1}
Result {resultId = 3, resultValue = 14}
Reading the output
- The second job has a negative cost, its worker throws, and the pool reports -1 for it instead of stopping.
- The results are sorted by id, so the run is deterministic even though the completion order is not.
- All three workers finish, so the main thread is not left waiting.
The next lesson collects the results and prints a summary.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What happens when a worker job throws?
Answer
The worker records a -1 result and continues
try and evaluate turn the exception into a value the pool can report.
-
How does the main thread know the workers are done?
Answer
It waits on a counter of finished workers with retry
Each worker increments the counter once, and the main waits for three.
-
Why are the results sorted by id?
Answer
The completion order varies and the page prints a stable order
The sort makes the output the same on every run.
-
What does this program print?
module Main (main) where main :: IO () main = print (2 + 3 :: Int)Answer
5
Two plus three is five.
-
What does
evaluateforce?Answer
The value to weak head normal form inside IO
It is what makes the exception appear in the worker.
-
What does this program print?
module Main (main) where main :: IO () main = print (length [1 .. 4 :: Int])Answer
4
The range has four elements.
-
What does
fromRight (-1)do?Answer
Returns the Right value or -1 for a Left
It is the default for the failure case.
-
What does this program print?
module Main (main) where import Data.Either (fromRight) main :: IO () main = print (fromRight 0 (Right 7 :: Either String Int))Answer
7
The Right value is returned.
-
What is the risk of not catching the exception?
Answer
The thread dies and the main thread waits for ever
A dead worker never increments the counter.
-
What does this program print?
module Main (main) where main :: IO () main = print (null [] :: Bool)Answer
True
The empty list is null.
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