51466bc655a93ffd6fbe165541c7e5f2e16665a6
[ghc-base.git] / GHC / IORef.hs
1 {-# OPTIONS_GHC -XNoImplicitPrelude -funbox-strict-fields #-}
2 {-# OPTIONS_HADDOCK hide #-}
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module      :  GHC.IORef
6 -- Copyright   :  (c) The University of Glasgow 2008
7 -- License     :  see libraries/base/LICENSE
8 -- 
9 -- Maintainer  :  cvs-ghc@haskell.org
10 -- Stability   :  internal
11 -- Portability :  non-portable (GHC Extensions)
12 --
13 -- The IORef type
14 --
15 -----------------------------------------------------------------------------
16 module GHC.IORef (
17     IORef(..),
18     newIORef, readIORef, writeIORef, atomicModifyIORef
19   ) where
20
21 import GHC.Base
22 import GHC.STRef
23 import GHC.IO
24
25 -- ---------------------------------------------------------------------------
26 -- IORefs
27
28 -- |A mutable variable in the 'IO' monad
29 newtype IORef a = IORef (STRef RealWorld a)
30
31 -- explicit instance because Haddock can't figure out a derived one
32 instance Eq (IORef a) where
33   IORef x == IORef y = x == y
34
35 -- |Build a new 'IORef'
36 newIORef    :: a -> IO (IORef a)
37 newIORef v = stToIO (newSTRef v) >>= \ var -> return (IORef var)
38
39 -- |Read the value of an 'IORef'
40 readIORef   :: IORef a -> IO a
41 readIORef  (IORef var) = stToIO (readSTRef var)
42
43 -- |Write a new value into an 'IORef'
44 writeIORef  :: IORef a -> a -> IO ()
45 writeIORef (IORef var) v = stToIO (writeSTRef var v)
46
47 atomicModifyIORef :: IORef a -> (a -> (a,b)) -> IO b
48 atomicModifyIORef (IORef (STRef r#)) f = IO $ \s -> atomicModifyMutVar# r# f s
49