HORIZON HASKELLDocslts/ghc-10.0.xfc4e5982026-10-11Search names, modules, packages, or :: a typeCtrl K

GHC 10.0.0.20260917 · lts/ghc-10.0.x · fc4e598 · 2026-10-11

Modulestrict-mutable-base-2.0.0.0Haskell2010

Data.IORef.Strict

Mutable references in the IO monad.

  • 1 type
  • 7 values
newtypenewtype IORef a
#

A mutable variable in the IO monad, which evaluates its content to Weak Head Normal Form.

Instances3NFData1, Eq, NFData
  • NFData1 IORefDefined in strict-mutable-base-2.0.0.0 · Data.IORef.Strict
  • Eq (IORef a)Defined in strict-mutable-base-2.0.0.0 · Data.IORef.Strict
  • NFData (IORef a)Defined in strict-mutable-base-2.0.0.0 · Data.IORef.Strict

Operations

7 declarations
valuereadIORef :: IORef a -> IO a
#

Read the value of an IORef.

Beware that the CPU executing a thread can reorder reads or writes to independent locations. See Data.IORef#memmodel for more details.

valuewriteIORef :: IORef a -> a -> IO ()
#

Write a new value into an IORef.

This function does not create a memory barrier and can be reordered with other independent reads and writes within a thread, which may cause issues for multithreaded execution. In these cases, consider using atomicWriteIORef instead. See Data.IORef#memmodel for more details.

Evaluates the new value to WHNF.

valueatomicModifyIORef :: IORef a -> (a -> (a, b)) -> IO b
#

Atomically modifies the contents of an IORef.

This function is useful for using IORef in a safe way in a multithreaded program. If you only have one IORef, then using atomicModifyIORef to access and modify it will prevent race conditions.

Extending the atomicity to multiple IORefs is problematic, so it is recommended that if you need to do anything more complicated then using MVar instead is a good idea.

Conceptually,

atomicModifyIORef ref f = do
  -- Begin atomic block
  old <- readIORef ref
  let r = f old
      new = fst r
  writeIORef ref new
  -- End atomic block
  case r of
    (_new, res) -> pure res

The actions in the section labeled "atomic block" are not subject to interference from other threads. In particular, it is impossible for the value in the IORef to change between the readIORef and writeIORef invocations.

Note that

atomicModifyIORef ref (\_ -> undefined)

will raise an exception in the calling thread, but will also install the bottoming value in the IORef, where it may be read by other threads.

This function imposes a memory barrier, preventing reordering around the "atomic block"; see Data.IORef#memmodel for details.

Evaluates both the new value and the returned value to WHNF.

valueatomicWriteIORef :: IORef a -> a -> IO ()
#

Variant of writeIORef. The prefix "atomic" relates to a fact that it imposes a reordering barrier, similar to atomicModifyIORef. Such a write will not be reordered with other reads or writes even on CPUs with weak memory model.

Evaluates the new value to WHNF.