Last active
December 16, 2015 16:49
-
-
Save AndrasKovacs/5466213 to your computer and use it in GitHub Desktop.
Dining philosophers solution with STM.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Control.Monad | |
import Control.Concurrent | |
import Control.Concurrent.STM | |
import System.Random | |
import Text.Printf | |
philosophers = ["Aristotle", "Kant", "Spinoza", "Marx", "Russel"] | |
waitSome = randomRIO (1000, 5000) >>= threadDelay . (*1000) | |
runPhilo :: String -> (TMVar Int, TMVar Int) -> IO () | |
runPhilo name (l, r) = forever $ do | |
printf "%s is waiting for the forks.\n" name | |
[lFork, rFork] <- atomically $ mapM takeTMVar [l, r] | |
printf "%s is eating with forks %d and %d.\n" name lFork rFork | |
waitSome | |
atomically $ zipWithM_ putTMVar [l, r] [lFork, rFork] | |
printf "%s is thinking.\n" name | |
waitSome | |
main = do | |
printf "Press enter to end dinner.\n\n" | |
forks <- mapM newTMVarIO [1..5] | |
zipWithM_ ((forkIO.) . runPhilo) philosophers (ap zip (tail . cycle) forks) | |
getLine |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment