Concurrency demos/Simple producer and consumer

From HaskellWiki
< Concurrency demos
Revision as of 08:49, 29 June 2007 by DonStewart (talk | contribs) (simple consumer/producer example)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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

    -- 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