【发布时间】:2018-01-05 08:18:09
【问题描述】:
我正在制作一个基于时间的唯一 ID 生成器来学习并发 Haskell 中的一些概念。
next 应该返回一个唯一的顺序 POSIX 时间,但这个时间戳不必与我接下来调用的确切时刻相匹配。
这段代码显然不会生成唯一的时间戳,我也不明白为什么:
import Control.Concurrent.Async (mapConcurrently)
import Data.Time.Clock.POSIX (getPOSIXTime)
import Data.Time (UTCTime)
import Control.Concurrent.STM (TMVar, atomically, takeTMVar, putTMVar, newTMVarIO)
import Data.List (nub)
getTime :: (Integral b, RealFrac a) => a -> IO b
getTime precision =
round . (* precision) . fromRational . toRational <$> getPOSIXTime
next :: Integral b => TMVar b -> IO b
next s = do
t <- getTime 1 -- one second precision
atomically $ do
v <- takeTMVar s
let t' = if t == v then t + 1 else t
putTMVar s t'
return t'
main = do
next' <- next <$> newTMVarIO 0
res <- mapConcurrently id [next' | _ <- [1 .. 100]]
print $ length $ nub res -- expected 100
【问题讨论】: