为什么这个Haskell程序实际上是并发的?

时间:2019-01-25 11:30:57

标签: haskell concurrency

我正在从Marlow的书Parallel and Concurrent Programming in Haskell中学习forkIOMvar的简单用法。我在 MVar作为共享状态容器部分中公开了以下代码:

-- Creates a new Map within an MVar
new :: IO PhoneBookState
new = do
  m <- newMVar Map.empty
  return (PhoneBookState m)

-- Inserts a Key, Value in the Map, locking the MVar
insert :: PhoneBookState -> Name -> PhoneNumber -> IO ()
insert (PhoneBookState m) name number = do
  book <- takeMVar m
  putMVar m (Map.insert name number book)

-- Retrieves the Map, locking the MVar briefly
lookup :: PhoneBookState -> Name -> IO (Maybe PhoneNumber)
lookup (PhoneBookState m) name = do
  book <- takeMVar m
  putMVar m book
  return (Map.lookup name book)

PhoneBookState持有MVar (Map Name PhoneNumber)的位置。我的问题出在main函数

main = do
  s <- new
  sequence_ [ insert s ("name" ++ show n) (show n) | n <- [1..10000] ]
  lookup s "name999" >>= print
  lookup s "unknown" >>= print

这个想法是两个查询同时发生,但是在这种情况下,它不应该是

main = do
  s <- new
  sequence_ [ insert s ("name" ++ show n) (show n) | n <- [1..10000] ]
  forkIO(lookup s "name999" >>= print)
  lookup s "unknown" >>= print

我想念什么?

0 个答案:

没有答案