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 import GHC.IORef hiding (atomicModifyIORef)
40 import qualified GHC.IORef
41 #if !defined(__PARALLEL_HASKELL__)
44 #endif /* __GLASGOW_HASKELL__ */
56 #if defined(__GLASGOW_HASKELL__) && !defined(__PARALLEL_HASKELL__)
57 -- |Make a 'Weak' pointer to an 'IORef'
58 mkWeakIORef :: IORef a -> IO () -> IO (Weak (IORef a))
59 mkWeakIORef r@(IORef (STRef r#)) f = IO $ \s ->
60 case mkWeak# r# r f s of (# s1, w #) -> (# s1, Weak w #)
63 -- |Mutate the contents of an 'IORef'
64 modifyIORef :: IORef a -> (a -> a) -> IO ()
65 modifyIORef ref f = readIORef ref >>= writeIORef ref . f
68 -- |Atomically modifies the contents of an 'IORef'.
70 -- This function is useful for using 'IORef' in a safe way in a multithreaded
71 -- program. If you only have one 'IORef', then using 'atomicModifyIORef' to
72 -- access and modify it will prevent race conditions.
74 -- Extending the atomicity to multiple 'IORef's is problematic, so it
75 -- is recommended that if you need to do anything more complicated
76 -- then using 'Control.Concurrent.MVar.MVar' instead is a good idea.
78 atomicModifyIORef :: IORef a -> (a -> (a,b)) -> IO b
79 #if defined(__GLASGOW_HASKELL__)
80 atomicModifyIORef = GHC.IORef.atomicModifyIORef
82 #elif defined(__HUGS__)
83 atomicModifyIORef = plainModifyIORef -- Hugs has no preemption
84 where plainModifyIORef r f = do
86 case f a of (a',b) -> writeIORef r a' >> return b
87 #elif defined(__NHC__)
88 atomicModifyIORef r f =
89 excludeFinalisers $ do