[Haskell-cafe] STM and random numbers

Tomasz Zielonka tomasz.zielonka at gmail.com
Sat Jan 13 03:36:23 EST 2007


On Sat, Jan 13, 2007 at 01:49:36PM +1000, Matthew Brecknell wrote:
> > Rather than having a separate thread computing the random numbers
> > using IO, why not just stick an StdGen in a TVar and write a function
> > like:
> > 
> > type RandomVar = TVar StdGen
> > 
> > rnd :: RandomVar -> STM a
> > rnd var = do
> >  g <- readTVar var
> >  let (r,g') = random g
> >  writeTVar var g'
> >  return r
> 
> The user of this approach should be aware that it may lead to
> non-determinism. That is, the sequence of psuedo-random numbers
> extracted by any one thread will depend on those extracted by other
> threads, which may in turn depend on the scheduling of those threads.
> 
> The TVar approach might also lead to excessive STM transaction
> abort-retry cycles, if multiple threads are retrieving many
> pseudo-random numbers via a single TVar.

As a workaround for these problems you can create a separate RandomVar
for each "atomically" block.

Best regards
Tomasz


More information about the Haskell-Cafe mailing list