This module exports:
MonadMutVartype class and its operations
- Instances of
- A universal pass-through instance of
MonadMutVarfor any existing
MonadMutVarwrapped by a
- The utility operations
- class Monad m => MonadMutVar ref m | m -> ref where
- atomicModifyRef' :: MonadMutVar ref m => ref a -> (a -> (a, b)) -> m b
- atomicWriteRef :: MonadMutVar ref m => ref a -> a -> m ()
- modifyRef :: MonadMutVar ref m => ref a -> (a -> a) -> m ()
- modifyRef' :: MonadMutVar ref m => ref a -> (a -> a) -> m ()
Create a new mutable variable holding the value supplied.
Return the current value stored in the mutable variable.
Write the supplied value into the mutable variable
Atomically modifies the contents of a mutable variable.
This function is useful for using mutable varibales in a safe way in a
multithreaded program. If you only have one mutable variable, then
atomicModifyRef to access and modify it will prevent race
Extending the atomicity to multiple mutable variables is problematic,
so it is recommended that if you need to do anything more complicated
MVar instead is a good idea.
atomicModifyRef does not apply the function strictly. This is
important to know even if all you are doing is replacing the value.
For example, this will leak memory:
ref <- newIORef 1 forever $ atomicModifyRef ref (\_ -> (2, ()))
Strict version of
atomicModifyRef. This forces both the value stored in
the mutable variable as well as the value returned.
Mutate the contents of a mutable variable.
Be warned that
modifyRef does not apply the function strictly. This means
if the program calls
modifyRef many times, but seldomly uses the value,
thunks will pile up in memory resulting in a space leak. This is a common
mistake made when using a mutable varible as a counter. For example, the
following will likely produce a stack overflow:
ref <- newRef 0 replicateM_ 1000000 $ modifyRef ref (+1) readRef ref >>= print
To avoid this problem, use