views:

32

answers:

2

Looking for a thread safe random generator I found a mersenne twister generator class that the author says if thread safe:

http://www.umiacs.umd.edu/~yangcj/mtrnd.html

But after studying the code I cannot see were it is safe thread. There are no locks of any kind or anything resembling a lock variable in there.

Is this implementation really thread safe? If so what is the magic?

A: 

It appears to be thread-safe in the sense that two different MersenneTwist objects can be used concurrently. You can't use the same object in two threads without protecting it with a lock.

I guess the original C version the author talks about used global or static variables so it's an improvement.

Amnon
My application requires to produce random but unique numbers among all threads. By using a different Mersenne Twist object per thread can I guarantee the uniqueness of the generated numbers?
Horacio
Generating unique numbers is a different question. Also, you will get the same sequence unless you give each object a different seed.
Amnon
As long as I use the same mersenne object I will get unique random numbers until the sequence repeats right? And for the mersenne twister the cycle repeats after a long period, far larger than what my app may need so I think I can use this random generator also as unique id generator. Correct me if wrong please.
Horacio
I don't know a lot about this topic, but I'm sure this is a wrong approach for a unique id generator. Like I said, this is a matter for a different question.
Amnon
It's quite obviously wrong. As the period of the Mersenne Twister is much, much longer as its range, it must repeat itself a lot earlier. Not particular to this PRNG, or even PRNGs in general. ALl RNG's must generate a non-unique result if they produce more results then the size of their output range. (Pigeonhole principle)
MSalters
+1  A: 

There is a discussion of how to make a multiple-stream Mersenne Twister random number generator at Multiple stream Mersenne Twister, and also an implementation (i.e., source code in Fortran 95) at http://theo.phys.sci.hiroshima-u.ac.jp/~ishikawa/PRNG/mt_stream_en.html. The method starts multiple streams at points in the Mersenne Twister sequence that are widely separated, guaranteeing that the multiple streams are independent of each other and won't produce the same random number sequence. There are no needs for locks and thus potential bottle necks in parallel code; the separate streams are accessed by id.

M. S. B.