Channels
A queue, not a box
A channel is an unbounded queue with two operations. A writer never blocks, because the queue can always grow; a reader blocks while the queue is empty. That is the difference from an MVar, where a put waits for a take:
newChan :: IO (Chan a)
writeChan :: Chan a -> a -> IO ()
readChan :: Chan a -> IO a
dupChan :: Chan a -> IO (Chan a)
dupChan is the unusual one: it returns a second channel that receives every value written to the first from then on, which is how a broadcast is built. The queue is in memory, so a producer that is much faster than its consumer grows the heap; the channel is a pipe and not a bounded buffer.
A producer and a consumer
module Main (main) where
import Control.Concurrent (forkIO)
import Control.Concurrent.Chan (newChan, readChan, writeChan)
import Control.Monad (forM_)
main :: IO ()
main = do
chan <- newChan
_ <- forkIO $ forM_ ["one", "two", "three"] (writeChan chan)
forM_ [1, 2, 3 :: Int] $ \_ -> readChan chan >>= putStrLn
ghc -Wall -O1 -threaded -o chan chan.hs
./chan
one
two
three
The producer writes all three values without waiting, and the consumer reads three and prints them. The order is the order of the writes, because the channel is a FIFO, and the program ends when the consumer has read all three: the three reads are the whole synchronisation, and no sleep is needed.
The order a channel keeps
The guarantees are worth stating exactly, because they are what a program can rely on:
- Values come out in the order they went in, from one writer; two writers interleave in some order and each writer's values stay in order.
- A write never blocks, so a producer cannot be slowed down by the consumer and the memory is the buffer.
- A read blocks until a value is there, and it wakes the oldest waiting reader first.
- A channel has no size, so there is no backpressure; a bounded queue needs the STM version of the next lessons.
No closing, and what replaces it
There is no close on a channel and no end marker, because a channel is a value and not a resource. A protocol that has to say "no more values" writes a sentinel value, which the consumer checks:
data Message = Job String | Stop
consumer chan = do
message <- readChan chan
case message of
Stop -> pure ()
Job name -> putStrLn name >> consumer chan
The alternative is an MVar that signals the end and a check before each read, which is two locks to get right. The sentinel is one constructor and one case, and it is what the capstone job runner uses for its shutdown. The STM of the next lesson gives a queue with retry and a bounded size, which is the other half of this design.
Exercises
- Add a second consumer and explain how the values are split.
- Use dupChan so that two consumers see every value.
- Write the sentinel protocol and a producer that sends three jobs and a stop.
- Explain why a fast producer can exhaust memory with a channel.
- Measure how many values a channel can hold before the heap grows noticeably.
- Replace the channel with an MVar and a list, and compare the code.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is a channel?
Answer
An unbounded FIFO queue with write and read
Many values, in order, with a write that never blocks.
-
When does
writeChanblock?Answer
Never
The queue is unbounded, so a write always succeeds.
-
When does
readChanblock?Answer
While the queue is empty
A reader waits for a value; that block is the synchronisation.
-
What does this program print?
module Main (main) where import Control.Concurrent.Chan (newChan, readChan, writeChan) main :: IO () main = do chan <- newChan writeChan chan (1 :: Int) writeChan chan 2 readChan chan >>= printAnswer
1
The channel is a FIFO, so the first read gives the first write.
-
How does a channel signal that no more values will come?
Answer
It does not: a sentinel value or an MVar says so
There is no close operation, so the protocol carries the end marker.
-
What does this program print?
module Main (main) where import Control.Concurrent.Chan (newChan, readChan, writeChan) import Control.Monad (forM_) main :: IO () main = do chan <- newChan forM_ [1, 2, 3 :: Int] (writeChan chan) a <- readChan chan b <- readChan chan print (a + b)Answer
3
The first two values are 1 and 2, so the sum is 3.
-
What does
dupChando?Answer
Returns a second channel that receives the later writes too
It is the broadcast primitive of the module.
-
Why can a fast producer exhaust memory?
Answer
The queue is unbounded and holds every value not yet read
There is no backpressure, so the queue is the buffer.
-
What does this program print?
module Main (main) where main :: IO () main = print (length [1 .. 3 :: Int])Answer
3
The range has three elements.
-
What does a bounded queue need that a channel lacks?
Answer
A size and a write that blocks when it is full
Backpressure is the missing feature, and the STM queue of the next lesson has it.
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