1 -----------------------------------------------------------------------------
4 -- Copyright : (c) The University of Glasgow 2001
5 -- License : BSD-style (see the file libraries/base/LICENSE)
7 -- Maintainer : libraries@haskell.org
8 -- Stability : experimental
9 -- Portability : portable
11 -- Mutable references in the IO monad.
13 -----------------------------------------------------------------------------
18 IORef, -- abstract, instance of: Eq, Typeable
19 newIORef, -- :: a -> IO (IORef a)
20 readIORef, -- :: IORef a -> IO a
21 writeIORef, -- :: IORef a -> a -> IO ()
22 modifyIORef, -- :: IORef a -> (a -> a) -> IO ()
23 atomicModifyIORef, -- :: IORef a -> (a -> (a,b)) -> IO b
25 #if !defined(__PARALLEL_HASKELL__) && defined(__GLASGOW_HASKELL__)
26 mkWeakIORef, -- :: IORef a -> IO () -> IO (Weak (IORef a))
30 import Prelude -- Explicit dependency helps 'make depend' do the right thing
36 #ifdef __GLASGOW_HASKELL__
37 import GHC.Base ( mkWeak#, atomicModifyMutVar# )
40 #if !defined(__PARALLEL_HASKELL__)
43 #endif /* __GLASGOW_HASKELL__ */
55 #if defined(__GLASGOW_HASKELL__) && !defined(__PARALLEL_HASKELL__)
56 -- |Make a 'Weak' pointer to an 'IORef'
57 mkWeakIORef :: IORef a -> IO () -> IO (Weak (IORef a))
58 mkWeakIORef r@(IORef (STRef r#)) f = IO $ \s ->
59 case mkWeak# r# r f s of (# s1, w #) -> (# s1, Weak w #)
62 -- |Mutate the contents of an 'IORef'
63 modifyIORef :: IORef a -> (a -> a) -> IO ()
64 modifyIORef ref f = writeIORef ref . f =<< readIORef ref
67 -- |Atomically modifies the contents of an 'IORef'.
69 -- This function is useful for using 'IORef' in a safe way in a multithreaded
70 -- program. If you only have one 'IORef', then using 'atomicModifyIORef' to
71 -- access and modify it will prevent race conditions.
73 -- Extending the atomicity to multiple 'IORef's is problematic, so it
74 -- is recommended that if you need to do anything more complicated
75 -- then using 'MVar' instead is a good idea.
77 atomicModifyIORef :: IORef a -> (a -> (a,b)) -> IO b
78 #if defined(__GLASGOW_HASKELL__)
79 atomicModifyIORef (IORef (STRef r#)) f = IO $ \s -> atomicModifyMutVar# r# f s
81 #elif defined(__HUGS__)
82 atomicModifyIORef = plainModifyIORef -- Hugs has no preemption
83 where plainModifyIORef r f = do
85 case f a of (a',b) -> writeIORef r a' >> return b
86 #elif defined(__NHC__)
87 atomicModifyIORef r f =
88 excludeFinalisers $ do