{- The dining philosophers, implemented with MVars -} module Main where import Concurrent -- hiding (QSem,newQSem, waitQSem, signalQSem) import System(getArgs) forever :: IO a -> IO a forever a = a >> forever a block :: IO () block = newEmptyMVar >>= takeMVar -- blocks calling thread indefinitely wait :: IO () wait = threadDelay 10000 philo :: [MVar ()] -> Int-> IO () philo chopsticks i = let num_phil = length (chopsticks) in do putStrLn ("Phil #"++(show i)++" thinks...") wait takeMVar (chopsticks !! i) -- wait takeMVar (chopsticks !! ((i+1) `mod` num_phil)) putStrLn ("Phil #"++(show i)++" eats...") wait putMVar (chopsticks !! i) () putMVar (chopsticks !! ((i+1) `mod` num_phil)) () philo chopsticks i main :: IO () main = do num_phil <- getArgs >>= \a-> return (read (head a)) chopsticks <- mapM (const (newMVar ())) [0.. num_phil-1] mapM_ (forkIO . (philo chopsticks)) [0.. num_phil-1] block