Capstone C: a clean shutdown

A clean shutdown

A worker that finds the queue empty has nothing to do but must not exit while the main thread may still add work. The design here is a stop flag in a TVar Bool and an orElse: a worker waits for a job or for the stop signal, whichever comes first, and counts itself out when it sees the signal.

next <- atomically $ (Left <$> readJob queue) `orElse` (Right <$> readStop stop)

The main thread waits until every job has a result, then writes the stop flag and waits for the finished counter. No worker is killed, so every worker leaves through the same path and the count is exact.

The program

module Main (main) where import Control.Concurrent (forkIO) import Control.Concurrent.STM import Control.Monad (replicateM_, unless, when) data Job = Job { jobId :: Int , jobCost :: Int } readJob :: TVar [Job] -> STM Job readJob queue = do jobs <- readTVar queue case jobs of [] -> retry job : rest -> writeTVar queue rest >> pure job readStop :: TVar Bool -> STM () readStop stop = do stopped <- readTVar stop unless stopped retry worker :: TVar [Job] -> TVar [(Int, Int)] -> TVar Bool -> TVar Int -> IO () worker queue results stop finished = loop where loop = do next <- atomically $ (Left <$> readJob queue) `orElse` (Right <$> readStop stop) case next of Left job -> do atomically (modifyTVar' results ((jobId job, jobCost job * 2) :)) loop Right () -> atomically (modifyTVar' finished (+ 1)) main :: IO () main = do let jobs = [Job n n | n <- [1 .. 6]] queue <- newTVarIO jobs results <- newTVarIO [] stop <- newTVarIO False finished <- newTVarIO 0 replicateM_ 3 (forkIO (worker queue results stop finished)) atomically $ do values <- readTVar results when (length values < length jobs) retry atomically (writeTVar stop True) atomically $ do done <- readTVar finished when (done < 3) retry values <- readTVarIO results print (length values, sum (map snd values))

ghc -Wall -O1 -threaded -o shutdown shutdown.hs
./shutdown

(6,42)

Reading the output

The next lesson adds a logger thread that owns the output.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does the worker wait for?

    Answer

    A job or the stop signal, whichever comes first

    The orElse combines the two transactions and the ready one wins.

  2. How does the main thread know the workers stopped?

    Answer

    It waits for the finished counter to reach three

    Each worker increments the counter on its way out.

  3. Why is no worker killed?

    Answer

    A killed worker could skip its count and leave the main thread waiting

    A cooperative stop is easier to count than an asynchronous kill.

  4. What does this program print? module Main (main) where main :: IO () main = print (sum [1 .. 6 :: Int])

    Answer

    21

    The sum of 1 to 6 is 21, and the doubles sum to 42.

  5. What does readStop do while the flag is False?

    Answer

    Retries

    The retry parks the transaction until the flag changes.

  6. What does this program print? module Main (main) where import Control.Concurrent.STM main :: IO () main = do flag <- newTVarIO False atomically (writeTVar flag True) readTVarIO flag >>= print

    Answer

    True

    The transaction set the flag and the read shows it.

  7. Why does the main thread wait for the results before stopping?

    Answer

    A stop before the last job would leave a job unprocessed

    The stop is the signal that no more work is coming.

  8. What does this program print? module Main (main) where main :: IO () main = print (2 * 21 :: Int)

    Answer

    42

    Two times 21 is 42.

  9. What does the finished counter count?

    Answer

    Workers that saw the stop signal

    A worker counts itself once on the way out.

  10. What does this program print? module Main (main) where main :: IO () main = print (null [1 :: Int])

    Answer

    False

    The list has an element.

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

Banner image