Search code examples
haskellconcurrencymonadsparallel-processingstm

Using the Par monad with STM and Deterministic IO


I'm in the process of writing a report for an assignment in which I implemented a concurrent multicore branch and bound algorithm using the STM package and there was an issue I've come up against.

The implementation which uses STM is obviously in the IO monad since it both uses STM's 'atomically' and Concurrent's 'forkIO', but it is deterministic. Despite the use of a shared memory variable, the final result of the function will always be the same for the same input.

My question is, what are my options when it comes to getting out of IO, besides 'unsafePerformIO'? Should I even try and get it out of the IO monad, since the use of multiple cores could potentially affect other concurrent code that doesn't have the same guarantee for determinism.

I've heard of the Par monad package (although not used it), but STM exists in the IO monad, and in order to get thread safe global variables my only alternative to STM is MVars (that I'm aware of), which also exist in the IO monad.


Solution

  • Please do not use unsafePerformIO with STM. STM has side-effects under the hood, using unsafePerformIO hides these side effects, making your code deceptively impure and thus hard or dangerous to refactor. Try harder to see if the parallel package will help you.

    One example of unsafe STM operations being unsafe is when you end up using the "pure" STM operation nested inside of another (perhaps by a higher level library). For example, the below code loops (terminates with <loop>) due to the nested STM operations. I recall older GHC versions crashing but can't seem to reproduce that behavior right now with GHC 7.0.1.

    import Control.Concurrent
    import Control.Concurrent.STM
    import System.IO.Unsafe
    import GHC.Conc.Sync
    
    main = newTVarIO 5 >>= runComputation >>= print
    
    runComputation :: TVar Int -> IO Int
    runComputation tv = atomically $ do
            let y = getFiveUnsafe tv + 1
            writeTVar tv y
            return y
    
    getFiveUnsafe tv = unsafePerformIO . atomically $ do
            x <- readTVar tv
            writeTVar tv (x + 5)
            return x
    

    (I welcome other people editing and adding more convincing examples - I believe better ones exist)