module Simulation.Aivika.Experiment.Concurrent.MVar
(maybeReadMVar,
maybePutMVar) where
import Control.Exception
import Control.Concurrent.MVar
import Data.Maybe
maybeReadMVar :: b -> (a -> IO b) -> MVar (Maybe a) -> IO b
maybeReadMVar b0 f x =
do a <- readMVar x
case a of
Just a -> f a
Nothing -> return b0
maybePutMVar :: MVar (Maybe a) -> IO a -> (a -> IO b) -> IO b
maybePutMVar x m0 f =
mask_ $
do a <- takeMVar x
case a of
Just a ->
do putMVar x (Just a)
f a
Nothing ->
do let handle :: SomeException -> IO a
handle e = do putMVar x Nothing
throw e
a0 <- catch m0 handle
putMVar x (Just a0)
f a0