1 {-# LANGUAGE CPP, NoImplicitPrelude, MagicHash, UnboxedTuples #-}
3 -----------------------------------------------------------------------------
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 : portable
13 -- Mutable references in the IO monad.
15 -----------------------------------------------------------------------------
20 IORef, -- abstract, instance of: Eq, Typeable
21 newIORef, -- :: a -> IO (IORef a)
22 readIORef, -- :: IORef a -> IO a
23 writeIORef, -- :: IORef a -> a -> IO ()
24 modifyIORef, -- :: IORef a -> (a -> a) -> IO ()
25 atomicModifyIORef, -- :: IORef a -> (a -> (a,b)) -> IO b
27 #if !defined(__PARALLEL_HASKELL__) && defined(__GLASGOW_HASKELL__)
28 mkWeakIORef, -- :: IORef a -> IO () -> IO (Weak (IORef a))
36 #ifdef __GLASGOW_HASKELL__
40 import GHC.IORef hiding (atomicModifyIORef)
41 import qualified GHC.IORef
42 #if !defined(__PARALLEL_HASKELL__)
45 #endif /* __GLASGOW_HASKELL__ */
57 #if defined(__GLASGOW_HASKELL__) && !defined(__PARALLEL_HASKELL__)
58 -- |Make a 'Weak' pointer to an 'IORef'
59 mkWeakIORef :: IORef a -> IO () -> IO (Weak (IORef a))
60 mkWeakIORef r@(IORef (STRef r#)) f = IO $ \s ->
61 case mkWeak# r# r f s of (# s1, w #) -> (# s1, Weak w #)
64 -- |Mutate the contents of an 'IORef'
65 modifyIORef :: IORef a -> (a -> a) -> IO ()
66 modifyIORef ref f = readIORef ref >>= writeIORef ref . f
69 -- |Atomically modifies the contents of an 'IORef'.
71 -- This function is useful for using 'IORef' in a safe way in a multithreaded
72 -- program. If you only have one 'IORef', then using 'atomicModifyIORef' to
73 -- access and modify it will prevent race conditions.
75 -- Extending the atomicity to multiple 'IORef's is problematic, so it
76 -- is recommended that if you need to do anything more complicated
77 -- then using 'Control.Concurrent.MVar.MVar' instead is a good idea.
79 atomicModifyIORef :: IORef a -> (a -> (a,b)) -> IO b
80 #if defined(__GLASGOW_HASKELL__)
81 atomicModifyIORef = GHC.IORef.atomicModifyIORef
83 #elif defined(__HUGS__)
84 atomicModifyIORef = plainModifyIORef -- Hugs has no preemption
85 where plainModifyIORef r f = do
87 case f a of (a',b) -> writeIORef r a' >> return b
88 #elif defined(__NHC__)
89 atomicModifyIORef r f =
90 excludeFinalisers $ do