1 {-# LANGUAGE CPP, NoImplicitPrelude #-}
3 -----------------------------------------------------------------------------
5 -- Module : Control.Concurrent.MVar
6 -- Copyright : (c) The University of Glasgow 2001
7 -- License : BSD-style (see the file libraries/base/LICENSE)
9 -- Maintainer : libraries@haskell.org
10 -- Stability : experimental
11 -- Portability : non-portable (concurrency)
13 -- Synchronising variables
15 -----------------------------------------------------------------------------
17 module Control.Concurrent.MVar
21 , newEmptyMVar -- :: IO (MVar a)
22 , newMVar -- :: a -> IO (MVar a)
23 , takeMVar -- :: MVar a -> IO a
24 , putMVar -- :: MVar a -> a -> IO ()
25 , readMVar -- :: MVar a -> IO a
26 , swapMVar -- :: MVar a -> a -> IO a
27 , tryTakeMVar -- :: MVar a -> IO (Maybe a)
28 , tryPutMVar -- :: MVar a -> a -> IO Bool
29 , isEmptyMVar -- :: MVar a -> IO Bool
30 , withMVar -- :: MVar a -> (a -> IO b) -> IO b
31 , modifyMVar_ -- :: MVar a -> (a -> IO a) -> IO ()
32 , modifyMVar -- :: MVar a -> (a -> IO (a,b)) -> IO b
34 , addMVarFinalizer -- :: MVar a -> IO () -> IO ()
39 import Hugs.ConcBase ( MVar, newEmptyMVar, newMVar, takeMVar, putMVar,
40 tryTakeMVar, tryPutMVar, isEmptyMVar,
44 #ifdef __GLASGOW_HASKELL__
45 import GHC.MVar ( MVar, newEmptyMVar, newMVar, takeMVar, putMVar,
46 tryTakeMVar, tryPutMVar, isEmptyMVar, addMVarFinalizer
50 #ifdef __GLASGOW_HASKELL__
56 import Control.Exception.Base
59 This is a combination of 'takeMVar' and 'putMVar'; ie. it takes the value
60 from the 'MVar', puts it back, and also returns it.
62 readMVar :: MVar a -> IO a
70 Take a value from an 'MVar', put a new value into the 'MVar' and
71 return the value taken. Note that there is a race condition whereby
72 another process can put something in the 'MVar' after the take
73 happens but before the put does.
75 swapMVar :: MVar a -> a -> IO a
83 'withMVar' is a safe wrapper for operating on the contents of an
84 'MVar'. This operation is exception-safe: it will replace the
85 original contents of the 'MVar' if an exception is raised (see
88 {-# INLINE withMVar #-}
89 -- inlining has been reported to have dramatic effects; see
90 -- http://www.haskell.org//pipermail/haskell/2006-May/017907.html
91 withMVar :: MVar a -> (a -> IO b) -> IO b
95 b <- restore (io a) `onException` putMVar m a
100 A safe wrapper for modifying the contents of an 'MVar'. Like 'withMVar',
101 'modifyMVar' will replace the original contents of the 'MVar' if an
102 exception is raised during the operation.
104 {-# INLINE modifyMVar_ #-}
105 modifyMVar_ :: MVar a -> (a -> IO a) -> IO ()
107 mask $ \restore -> do
109 a' <- restore (io a) `onException` putMVar m a
113 A slight variation on 'modifyMVar_' that allows a value to be
114 returned (@b@) in addition to the modified value of the 'MVar'.
116 {-# INLINE modifyMVar #-}
117 modifyMVar :: MVar a -> (a -> IO (a,b)) -> IO b
119 mask $ \restore -> do
121 (a',b) <- restore (io a) `onException` putMVar m a