Cartesius00
Cartesius00

Reputation: 24414

Random number generators and thread safety

Almost every pseudorandom generator in C/C++ (Mersenne, ...) uses some kind of internal state, usually a short vector of bytes. My question is, when such a random generator is used and shared in a multithreaded environment is it "much" better to have it thread-safe or letting "race conditions" to occur can only increases randomness?

I know this question is extremely hard to answer rigorously but will appreciate any opinions.

Upvotes: 2

Views: 940

Answers (3)

MvG
MvG

Reputation: 61097

Concurrent write

It highly depends on the kind of internal state. If every possible bit pattern is a valid representation of internal state, and will therefore occur at some point of the random number sequence, then having write races should be no problem. But many random number generators, including the Mersenne you quoted, have a period which is not a power of 256, therefore have some state patterns which are never reached in single-threaded operation and might cause problems in multi-threaded operation.

Concurrent read

But there is an even better reason to make the rng thread-safe: otherwise two processes might read the same state before either one can update it. This can lead to two processes sharing exactly the same random number, which can lead to all kinds of bizarre problems, depending on your application. You can make it thread-sdafe either using mutexes or thread-local state.

Upvotes: 3

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234674

Letting "race conditions" occur can mess up everything. Technically, a data race is undefined behaviour, so it could order pizza.

But even if that doesn't happen, the internal state is likely to get corrupted and all important properties of the random sequence will just be lost. You can no longer guarantee uniformity, for example. You can't leave the generation of random numbers to chance.

Upvotes: 10

Alex Wilson
Alex Wilson

Reputation: 6740

Letting race conditions occur is never better. Your code may crash. Even if it doesn't, this is almost certain to degrade the quality of the numbers generated. People spend a lot of effort designing random number generators and injecting this sort of noise is highly likely to sabotage their efforts.

Upvotes: 5

Related Questions