module Control.Concurrent.Classy.STM.TSem
( TSem
, newTSem
, waitTSem
, signalTSem
, signalTSemN
) where
import Control.Monad (when)
import Control.Monad.STM.Class
import Numeric.Natural (Natural)
newtype TSem stm = TSem (TVar stm Integer)
newTSem :: MonadSTM stm => Integer -> stm (TSem stm)
newTSem :: forall (stm :: * -> *). MonadSTM stm => Integer -> stm (TSem stm)
newTSem Integer
i = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall (stm :: * -> *). TVar stm Integer -> TSem stm
TSem (forall (stm :: * -> *) a. MonadSTM stm => a -> stm (TVar stm a)
newTVar forall a b. (a -> b) -> a -> b
$! Integer
i)
waitTSem :: MonadSTM stm => TSem stm -> stm ()
waitTSem :: forall (stm :: * -> *). MonadSTM stm => TSem stm -> stm ()
waitTSem (TSem TVar stm Integer
t) = do
Integer
i <- forall (stm :: * -> *) a. MonadSTM stm => TVar stm a -> stm a
readTVar TVar stm Integer
t
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Integer
i forall a. Ord a => a -> a -> Bool
<= Integer
0) forall (stm :: * -> *) a. MonadSTM stm => stm a
retry
forall (stm :: * -> *) a. MonadSTM stm => TVar stm a -> a -> stm ()
writeTVar TVar stm Integer
t forall a b. (a -> b) -> a -> b
$! (Integer
iforall a. Num a => a -> a -> a
-Integer
1)
signalTSem :: MonadSTM stm => TSem stm -> stm ()
signalTSem :: forall (stm :: * -> *). MonadSTM stm => TSem stm -> stm ()
signalTSem (TSem TVar stm Integer
t) = do
Integer
i <- forall (stm :: * -> *) a. MonadSTM stm => TVar stm a -> stm a
readTVar TVar stm Integer
t
forall (stm :: * -> *) a. MonadSTM stm => TVar stm a -> a -> stm ()
writeTVar TVar stm Integer
t forall a b. (a -> b) -> a -> b
$! Integer
iforall a. Num a => a -> a -> a
+Integer
1
signalTSemN :: MonadSTM stm => Natural -> TSem stm -> stm ()
signalTSemN :: forall (stm :: * -> *).
MonadSTM stm =>
Natural -> TSem stm -> stm ()
signalTSemN Natural
0 TSem stm
_ = forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
signalTSemN Natural
1 TSem stm
s = forall (stm :: * -> *). MonadSTM stm => TSem stm -> stm ()
signalTSem TSem stm
s
signalTSemN Natural
n (TSem TVar stm Integer
t) = do
Integer
i <- forall (stm :: * -> *) a. MonadSTM stm => TVar stm a -> stm a
readTVar TVar stm Integer
t
forall (stm :: * -> *) a. MonadSTM stm => TVar stm a -> a -> stm ()
writeTVar TVar stm Integer
t forall a b. (a -> b) -> a -> b
$! Integer
i forall a. Num a => a -> a -> a
+ forall a. Integral a => a -> Integer
toInteger Natural
n