[Haskell-cafe] unsafeInerleaveIO and randomIO

Matthew Brecknell haskell at brecknell.org
Tue Apr 17 07:32:03 EDT 2007


Bertram Felgenhauer:
> > unsafeInterleaveSequence :: [IO a] -> IO [a]
> > unsafeInterleaveSequence []     = return []
> > unsafeInterleaveSequence (x:xs) =
> >      unsafeInterleaveIO $ liftM2 (:) x (unsafeInterleaveSequence xs)
> > 
> > randomInts = unsafeInterleaveSequence $ repeat randomIO

I took a peek at GHC's Random.hs to get an idea of how "unsafe" this
approach might be. I see that theStdGen is stored in an IORef, and that
newStdGen and getStdGen are implemented in terms of the unsynchronised
getStdGen and setStdGen. I guess this allows a race condition in which
randomIO and friends could return duplicate random numbers in different
threads?

Something like this might be better:

> getStdRandom f = atomicModifyIORef theStdGen (swap . f)
>   where swap (v,g) = (g,v)
> newStdGen = atomicModifyIORef theStdGen split

Now let's see if I can figure out how to submit my first patch...



More information about the Haskell-Cafe mailing list