-- prodcon-mvar.hs
-- producer/consumer example in Concurrent Haskell using MVar buffer

import Control.Concurrent
import Control.Concurrent.MVar

producer :: MVar Int -> Int -> IO ()
producer buf 0 = return ()
producer buf n = putMVar buf n >> producer buf (n-1)

consumer :: MVar Int -> IO ()
consumer buf = takeMVar buf >>= print >> consumer buf

run n = do buf <- newEmptyMVar
           forkIO (consumer buf)
           producer buf n

-- The parent process runs producer and will terminate. The child
-- process running consumer will block trying to execute takeMVar
-- on the empty buf MVar after the producer is finished.
