Question

The caption pretty much says it.

PS. This is for C++ Windows program.

Was it helpful?

Solution

According to the MSDN documentation on srand() (assuming you are using Microsoft's C runtime library), the seed is thread-local, so you need to call srand() for each thread that is using rand(). Note that this may not be the case in other implementations.

Quoting from MSDN:

The srand function sets the starting point for generating a series of pseudorandom integers in the current thread.

OTHER TIPS

Even if the answer weren't platform specific I'd suggest you avoid srand() and use <random> instead. Not only does the C++11 <random> library provide clear semantics in multithreaded programs but it also provides much better facilities for random number generation. It provides several different random number generators to meet different quality, speed, and size requirements, and many standard distributions so you won't make the mistakes people often do when using rand.

No, as per the Standard, because once you call srand() it affects rand() calls from all threads.

C library function srand() is single-threaded just like all other functions are, which means if you call srand() from one thread, it affects the number-seqeunce generated from rand() in other threads as well.

But Microsoft provides non-standard srand() which does require you to call it from all threads.

Be aware that the state is fiber-local (which is more fine-grained than thread-local). Thus, srand has to be called for each fiber. (Of course, when you don't use fibers it's equivalent to thread-local.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top