Skip to content

Instantly share code, notes, and snippets.

@jabaraster
Created October 27, 2018 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jabaraster/2bc16357341b45f23b116cd45cbd58c5 to your computer and use it in GitHub Desktop.
Save jabaraster/2bc16357341b45f23b116cd45cbd58c5 to your computer and use it in GitHub Desktop.
プログラミング言語Rustの「食事する哲学者」をHaskellで書いてみた
module Main where
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.Async
import Control.Concurrent.MVar
data Philosopher = Philosopher {
name :: String
, left :: Int
, right :: Int
} deriving Show
data Table = Table {
forks :: [MVar ()]
}
eat :: Table -> Philosopher -> IO ()
eat table (Philosopher name left right) = do
let leftLock = (forks table) !! left
let rightLock = (forks table) !! right
_ <- takeMVar leftLock
threadDelay (150 * 10 ^ 3)
_ <- takeMVar rightLock
putStrLn (name ++ " start eating.")
threadDelay (1 * 10 ^ 6)
putStrLn (name ++ " finish eating.")
putMVar leftLock ()
putMVar rightLock ()
main :: IO ()
main =
let ps = [
Philosopher "Judith Butler" 0 1
, Philosopher "Gilles Deleuze" 1 2
, Philosopher "Karl Marx" 2 3
, Philosopher "Emma Goldman" 3 4
, Philosopher "Michel Foucault" 0 4
]
in
do
mvs <- mapM (\_ -> newMVar ()) [1..5]
let table = Table mvs
as <- mapM (async . eat table) ps
mapM_ wait as
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment