@@ -1,24 +1,27 @@
11module Network.Wai.Handler.Warp.Counter (
22 Counter
33 , newCounter
4− , isZero
4+ , waitForZero
55 , increase
66 , decrease
77 ) where
88
9−import Network.Wai.Handler.Warp.IORef
9+import Control.Concurrent.STM
10+import Control.Monad (unless)
1011import Control.Applicative ((<$>))
1112
12−newtype Counter = Counter (IORef Int)
13+newtype Counter = Counter (TVar Int)
1314
1415newCounter :: IO Counter
15−newCounter = Counter <$> newIORef 0
16+newCounter = Counter <$> newTVarIO 0
1617
17−isZero :: Counter -> IO Bool
18−isZero (Counter ref) = (== 0) <$> readIORef ref
18+waitForZero :: Counter -> IO ()
19+waitForZero (Counter ref) = atomically $ do
20+ x <- readTVar ref
21+ unless (x == 0) retry
1922
2023increase :: Counter -> IO ()
21−increase (Counter ref) = atomicModifyIORef' ref $ \x -> (x + 1, ())
24+increase (Counter ref) = atomically $ modifyTVar' ref $ \x -> x + 1
2225
2326decrease :: Counter -> IO ()
24−decrease (Counter ref) = atomicModifyIORef' ref $ \x -> (x - 1, ())
27+decrease (Counter ref) = atomically $ modifyTVar' ref $ \x -> x - 1