IORef
concurrencyicon.icon
Overview
IORef can store delayed computations.
Whole operation is performed atomically, without other threads interfering.
Function forces the value in the IORef and the value returned to WHNF.
The presence of atomicModifyIORef' allows modifications of a single IORef in a predictable way.
But operations involving several IORef s at once will always be unpredictable.
code:IORef.hs
import Data.IORef
data IORef a --abstract
newIORef :: a -> IO (IORef a)
readIORef :: IORef a-> IO a
writeIORef :: IORef a -> a -> IO ()
modifyIORef :: IORef a -> (a -> a) -> IO ()
modifyIORef' :: IORef a -> (a -> a) -> IO () -- Strict
Note: IORefs can store delayed computations.
atomicModifyIORef' :: IORef a ->(a -> (a, b))-> IO b
Function is applied to current value.
First component of result will become new value.
Second component of result is returned.
code:example.hs
transfer :: IORef Integer
-> IORef Integer
-> Integer
-> IO ()
transfer from to amount = do
atomicModifyIORef' from $ \ x -> (x - amount, ())
atomicModifyIORef' to $ \ x -> (x + amount, ())