Haskell 类型系统使STM Monad中不允许存在IO Monad, 然而atomically 的函数签名是STM a -> IO a,使函数类型为" ... -> STM (IO ())",可达到有限度混入IO的目的。例如:
module Main where
import Control.Concurrent.STM
withdraw account amount = do
(id, bal) <- readTVar account
check(amount <= 0 || bal >= amount )
writeTVar account (id, (bal-amount))
return $ putStrLn $ "withdraw " ++ show amount ++ " from " ++ id
关于STM的介绍,可见Beautiful Code(《代码之美》)第24章Beautiful Concurrency、和。
阅读(148) | 评论(0) | 转发(0) |