{-# LANGUAGE CPP, DeriveDataTypeable #-}
#if __GLASGOW_HASKELL__ >= 701
{-# LANGUAGE Trustworthy #-}
#endif
module Control.Concurrent.STM.TMVar (
#ifdef __GLASGOW_HASKELL__
TMVar,
newTMVar,
newEmptyTMVar,
newTMVarIO,
newEmptyTMVarIO,
takeTMVar,
putTMVar,
readTMVar,
tryReadTMVar,
swapTMVar,
tryTakeTMVar,
tryPutTMVar,
isEmptyTMVar
#endif
) where
#ifdef __GLASGOW_HASKELL__
import GHC.Conc
import Data.Typeable (Typeable)
newtype TMVar a = TMVar (TVar (Maybe a)) deriving (Eq, Typeable)
newTMVar :: a -> STM (TMVar a)
newTMVar a = do
t <- newTVar (Just a)
return (TMVar t)
newTMVarIO :: a -> IO (TMVar a)
newTMVarIO a = do
t <- newTVarIO (Just a)
return (TMVar t)
newEmptyTMVar :: STM (TMVar a)
newEmptyTMVar = do
t <- newTVar Nothing
return (TMVar t)
newEmptyTMVarIO :: IO (TMVar a)
newEmptyTMVarIO = do
t <- newTVarIO Nothing
return (TMVar t)
takeTMVar :: TMVar a -> STM a
takeTMVar (TMVar t) = do
m <- readTVar t
case m of
Nothing -> retry
Just a -> do writeTVar t Nothing; return a
tryTakeTMVar :: TMVar a -> STM (Maybe a)
tryTakeTMVar (TMVar t) = do
m <- readTVar t
case m of
Nothing -> return Nothing
Just a -> do writeTVar t Nothing; return (Just a)
putTMVar :: TMVar a -> a -> STM ()
putTMVar (TMVar t) a = do
m <- readTVar t
case m of
Nothing -> do writeTVar t (Just a); return ()
Just _ -> retry
tryPutTMVar :: TMVar a -> a -> STM Bool
tryPutTMVar (TMVar t) a = do
m <- readTVar t
case m of
Nothing -> do writeTVar t (Just a); return True
Just _ -> return False
readTMVar :: TMVar a -> STM a
readTMVar (TMVar t) = do
m <- readTVar t
case m of
Nothing -> retry
Just a -> return a
tryReadTMVar :: TMVar a -> STM (Maybe a)
tryReadTMVar (TMVar t) = readTVar t
swapTMVar :: TMVar a -> a -> STM a
swapTMVar (TMVar t) new = do
m <- readTVar t
case m of
Nothing -> retry
Just old -> do writeTVar t (Just new); return old
isEmptyTMVar :: TMVar a -> STM Bool
isEmptyTMVar (TMVar t) = do
m <- readTVar t
case m of
Nothing -> return True
Just _ -> return False
#endif