Concurrency demos/Simple producer and consumer

From HaskellWiki

A simple example of a producer thread, performing IO events, and passing them over a Chan, to a consumer thread, which processes the events as they arrive (in a pure manner).

The interesting point to note is that Chans abstract over unsafeInterleaveIO, and allow for pure processing of streams of external events.

import Data.Char
import Control.Concurrent
import Control.Concurrent.Chan

main = do
    c  <- newChan
    cs <- getChanContents c     -- a lazy stream of events from eventReader
    forkIO (producer c)          -- char producer
    consumer cs

  where
    -- thread one: the event producer
    producer c = forever $ do
        key <- getChar
        writeChan c key

    -- thread two: the lazy consumer
    consumer = mapM_ print . map shift
        where shift c | isAlpha c = chr (ord c + 1)
                      | otherwise = c

forever a = a >> forever a

And running it:

   $ ghc -O -threaded A.hs -o a
   $ ./a
   a
   'b'
   '\n'
   b
   'c'
   '\n'
   d
   'e'
   '\n'