Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safe mersenne twister

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?

like image 565
Horacio Avatar asked Jul 01 '10 13:07

Horacio


People also ask

Is Mersenne Twister thread safe?

This particular function is thread safe. It is OK to create random number generators, engines and distributions, and call generate a number in a function local engine in multiple threads.

Is CPP thread safe?

It's safe to read and write to one instance of a type even if another thread is reading or writing to a different instance of the same type. For example, given objects A and B of the same type, it's safe when A is being written in thread 1 and B is being read in thread 2.

Is random seed thread safe?

Both the functions on the “random” module are thread safe as are the methods on an instance of the random. Random class. This means that a multithreaded program may call module functions in order to generate random numbers with a seed and sequence of random numbers shared between threads, or have a single new random.

Is Rand thread safe?

rand() is not threadsafe, but rand_r() is. The rand() function generates a pseudo-random integer in the range 0 to RAND_MAX (macro defined in <stdlib. h>). Use the srand() function before calling rand() to set a starting point for the random number generator.


2 Answers

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.

like image 183
M. S. B. Avatar answered Oct 19 '22 10:10

M. S. B.


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.

like image 23
Amnon Avatar answered Oct 19 '22 12:10

Amnon