Thread-safety of IORef is dangerously ambiguous
Currently the documentation of Data.IORef
is quite ambiguous regarding the safety of using IORef
s in multi-threaded programs. In particular, we provide atomicModifyIORef
and friends, which are safe to use in a multi-threaded program. However, we do not provide atomicReadIORef
(although technically atomicModifyIORef
can be used to implement it albeit inefficiently). Consequently users are tempted to use readIORef
despite the fact that this is unsafe (as these operations lack the necessary barriers to guarantee consistent memory ordering). Given that GHC itself contains such incorrect uses (e.g. in GHC.Utils.TmpFs
) I think we should do something to hide this foot-gun.
I can see two options:
- Introduce
atomicReadIORef
operations and clearly mark the non-atomic operations as unsafe for concurrent access - Give
readIORef
the necessary barriers. We could in principle continue to use the non-barrier'd operations inSTRef
.