packages feed

caf-0.0.2: Examples/Example04.hs

module Control.Concurrent.Futures.Example04 where
import qualified Control.Concurrent.Futures.BChan as BChan
import qualified Control.Concurrent.Futures.Futures as Futures
import Control.Concurrent

-- local finals
oneSecond = 1000000

  --------------------------------------------------------------------------------
-- | Producer Consumer Example for bounded channels using 'Futures.withFuturesDo'.
bchannelExampleF :: IO ()
bchannelExampleF = return () --Futures.withFuturesDo bchannelExample

-- | Producer Consumer Example for bounded channels.
bchannelExample :: IO ()
bchannelExample = do
 putStrLn $ "Producer-Consumer example with channels"
 channel <- BChan.newBChan 5
 Control.Concurrent.forkIO $ (produceb 10 channel)
 Control.Concurrent.forkIO $ (consumeb channel)
 Control.Concurrent.threadDelay $ 10 * oneSecond

--consumeb :: (Show a) => BChan.BChan a -> IO b
consumeb chan = do
 putStrLn $ "Trying to read..."
 val <- BChan.readBChan chan
 putStrLn $ "read new value: " ++ show val
 Control.Concurrent.threadDelay oneSecond
 consumeb chan
 return ()

--produceb :: (Num a) => a -> BChan.BChan a  -> IO ()
produceb n chan = do
 case n of
  0 -> BChan.writeBChan chan n
  otherwise -> do
   BChan.writeBChan chan n
   Control.Concurrent.threadDelay oneSecond
   produceb (n-1) chan