Reputation: 1256
I need to use random in a multi-threaded loop, but require the same values through each loop independent of which thread is evaluating that cycle.
Without multi-threading I can do:
seed(1)
for (unsigned int i=0; i<100; i++){
rand()
}
Within the loop each time rand() will be called it will return a new pseudo-random value. Now I want to create the same list multi-threaded.
The main reason is that I need the same sequence of pseudo-random numbers independent of the order of the loop (so more like based on 'i' within the loop).
Note: I've been going through many 'random' and 'multithreading' topics but only found solutions on how to make sure the numbers are always random, not the other way around.
EDIT:
The result should be as if based on a seed a random list is created. And that random list should be used within the loop with index 'i' to get the pseudo-random value. So within the loop the same random number will be at index 'i' based on the seed. (Yet there shouldn't be a single random number same throughout the loop. But the sequence should be the same for each program run. Independent of number of threads or which thread is evaluating a part of the cycle.)
It wouldn't be very efficient to create that list (non-multithreaded) and use that initialized list within the multithreaded loop. Any thoughts on this?
Upvotes: 3
Views: 568
Reputation: 572
You need a counter-based random generator, instead of a congruential one. A good document explaining how they work is here:
http://www.thesalmons.org/john/random123/papers/random123sc11.pdf
Upvotes: 3
Reputation: 19104
Use any non-STDC random number generator, with a separately manageable state. I recommend this: http://www.boost.org/doc/libs/1_52_0/doc/html/boost_random.html
Upvotes: 4