1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
2 -----------------------------------------------------------------------------
5 -- Copyright : (c) The University of Glasgow 2001
6 -- License : BSD-style (see the file libraries/base/LICENSE)
8 -- Maintainer : libraries@haskell.org
9 -- Stability : experimental
10 -- Portability : portable
12 -- Mutable references in the IO monad.
14 -----------------------------------------------------------------------------
19 IORef, -- abstract, instance of: Eq, Typeable
20 newIORef, -- :: a -> IO (IORef a)
21 readIORef, -- :: IORef a -> IO a
22 writeIORef, -- :: IORef a -> a -> IO ()
23 modifyIORef, -- :: IORef a -> (a -> a) -> IO ()
24 atomicModifyIORef, -- :: IORef a -> (a -> (a,b)) -> IO b
26 #if !defined(__PARALLEL_HASKELL__) && defined(__GLASGOW_HASKELL__)
27 mkWeakIORef, -- :: IORef a -> IO () -> IO (Weak (IORef a))
35 #ifdef __GLASGOW_HASKELL__
39 #if !defined(__PARALLEL_HASKELL__)
42 #endif /* __GLASGOW_HASKELL__ */
54 #if defined(__GLASGOW_HASKELL__) && !defined(__PARALLEL_HASKELL__)
55 -- |Make a 'Weak' pointer to an 'IORef'
56 mkWeakIORef :: IORef a -> IO () -> IO (Weak (IORef a))
57 mkWeakIORef r@(IORef (STRef r#)) f = IO $ \s ->
58 case mkWeak# r# r f s of (# s1, w #) -> (# s1, Weak w #)
61 -- |Mutate the contents of an 'IORef'
62 modifyIORef :: IORef a -> (a -> a) -> IO ()
63 modifyIORef ref f = readIORef ref >>= writeIORef ref . f
66 -- |Atomically modifies the contents of an 'IORef'.
68 -- This function is useful for using 'IORef' in a safe way in a multithreaded
69 -- program. If you only have one 'IORef', then using 'atomicModifyIORef' to
70 -- access and modify it will prevent race conditions.
72 -- Extending the atomicity to multiple 'IORef's is problematic, so it
73 -- is recommended that if you need to do anything more complicated
74 -- then using 'Control.Concurrent.MVar.MVar' instead is a good idea.
76 atomicModifyIORef :: IORef a -> (a -> (a,b)) -> IO b
77 #if defined(__GLASGOW_HASKELL__)
78 atomicModifyIORef (IORef (STRef r#)) f = IO $ \s -> atomicModifyMutVar# r# f s
80 #elif defined(__HUGS__)
81 atomicModifyIORef = plainModifyIORef -- Hugs has no preemption
82 where plainModifyIORef r f = do
84 case f a of (a',b) -> writeIORef r a' >> return b
85 #elif defined(__NHC__)
86 atomicModifyIORef r f =
87 excludeFinalisers $ do