R – Producer and consumer problem in Haskell

concurrencyfunctional programminghaskellmultithreading

I would like to how can we implement producer/consumer in a functional programming language like Haskell? and how it will be different from an Imperative language? My understanding of functional programming language is primitive. Any help will be appreciated.

Best Answer

A producer/consumer abstraction using preemptive threads and messages passed through a channel:

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

You would use a similar model in Erlang. Threads to represent the consumer and producer, and a shared pipe of messages between them, each acting asynchronously.