Capstone C: logging without a race
One thread owns the output
Workers that print directly interleave their lines and the output becomes unreadable. The fix is a logger thread: workers write a line to a Chan String and one thread reads the channel and prints. The channel keeps the order of the writes it received, and the workers never touch the terminal.
logger input done = loop
where
loop = do
line <- readChan input
putStrLn line
if line == "stop" then writeChan done line else loop
The "stop" line is the sentinel the channels lesson described: there is no close on a channel, so the protocol carries the end marker. The main thread sends it after the last worker is done and waits for the logger to acknowledge.
The program
module Main (main) where
import Control.Concurrent (forkIO)
import Control.Concurrent.Chan (Chan, newChan, readChan, writeChan)
import Control.Concurrent.STM
import Control.Monad (replicateM_, when)
data Job = Job
{ jobId :: Int
, jobCost :: Int
}
logger :: Chan String -> Chan String -> IO ()
logger input done = loop
where
loop = do
line <- readChan input
putStrLn line
if line == "stop"
then writeChan done line
else loop
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)
worker :: TVar [Job] -> TVar [Int] -> TVar Int -> Chan String -> IO ()
worker queue results finished logChan = loop
where
loop = do
next <- atomically (readJob queue)
case next of
Nothing -> atomically (modifyTVar' finished (+ 1))
Just job -> do
writeChan logChan ("job " ++ show (jobId job) ++ " done")
atomically (modifyTVar' results (jobCost job * 2 :))
loop
main :: IO ()
main = do
logChan <- newChan
loggerDone <- newChan
_ <- forkIO (logger logChan loggerDone)
queue <- newTVarIO [Job 1 5, Job 2 7, Job 3 3]
results <- newTVarIO []
finished <- newTVarIO 0
replicateM_ 3 (forkIO (worker queue results finished logChan))
atomically $ do
done <- readTVar finished
when (done < 3) retry
writeChan logChan "stop"
_ <- readChan loggerDone
values <- readTVarIO results
print (length values, sum values)
ghc -Wall -O1 -threaded -o logging logging.hs
./logging
job 1 done
job 2 done
job 3 done
stop
(3,30)
Reading the output
- The three job lines are the order the logger received them; with three workers the order can differ between runs, and the count and the sum at the end do not.
- The stop line is printed by the logger like any other, which is the sentinel in action.
- The last line is printed by the main thread after the logger acknowledged, so no log line can be lost at exit.
The next lesson tests the pool a hundred times and reports the flakiness that is real.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Why does one thread own the output?
Answer
Workers that print directly interleave their lines
A single logger serialises the lines.
-
How does the logger learn that the log is finished?
Answer
A sentinel line "stop" and a second channel to acknowledge
A channel has no close, so the protocol carries the marker.
-
What order do the log lines have?
Answer
The order the logger received them, which can vary between runs
The workers race to write, and the channel keeps the arrival order.
-
What does this program print?
module Main (main) where main :: IO () main = putStrLn "job 1 done"Answer
job 1 done
putStrLn prints the string without quotes.
-
What does
readChando on an empty channel?Answer
Blocks until a value arrives
The block is what keeps the logger waiting for the next line.
-
What does this program print?
module Main (main) where main :: IO () main = print (length ["a", "b", "c"])Answer
3
The list has three strings.
-
What does the final line of the output prove?
Answer
The main thread waited for the logger to finish
The count and the sum are printed after the acknowledgement.
-
What does this program print?
module Main (main) where main :: IO () main = print (sum [5, 7, 3 :: Int])Answer
15
The three costs add to 15, and their doubles to 30.
-
Why is the log order not guaranteed to be the job order?
Answer
The three workers run at the same time and write when they finish
The completion order is up to the runtime.
-
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