[Haskell-cafe] Haskell memory model

Li-yao Xia lysxia at gmail.com
Sun Mar 4 15:21:54 UTC 2018

Hello café,

What guarantees are there about shared memory concurrency in Haskell? In 
particular, I'm wondering how to correctly and efficiently synchronize 
mutable operations from the vector package, using stm or atomic-primops.

- Are reads/writes on vectors sequentially consistent? As a concrete 
example, can the following program (a common test for relaxed memory 
models) print anything?

import qualified Data.Vector.Mutable as MV
import Control.Concurrent

main :: IO ()
main = do
   v <- MV.replicate 2 0
   t <- newEmptyMVar
   forkIO $ do
     MV.write v 0 1
     x <- MV.read v 1
     putMVar t x
   forkIO $ do
     MV.write v 1 1
     x <- MV.read v 0
     putMVar t x
   a <- takeMVar t
   b <- takeMVar t
   if a == 0 && b == 0 then
     putStrLn "Relaxed!"
     return ()

- Do atomic operations (via stm or atomic-primops) imply some 
constraints between vector operations? As another concrete example, can 
the snippet linked below ever throw an exception? One thread writes to a 
vector, and another reads from it, and they communicate via stm to guess 
whether the read value is safe to evaluate (in one test case the first 
thread overwrites a defined value with undefined, and in the other case 
it overwrites undefined with a defined value).



More information about the Haskell-Cafe mailing list