Is std::random_shuffle threadsafe? I presume not since the regular rand() is not threadsafe. If that is the case, how would I use rand_r with random_shuffle so that I can give each thread a unique seed. I've seen examples of using custom random generators with random_shuffle, but it is still unclear to me.
Thanks.
You need to provide a random number generator function or functor object that takes an integral value type and returns another value of some integral type that will not overflow the bounds of the container that the iterators you've passed into the function are iterating through. Also in the case of a functor object, it must implement the
operator()
so that it can be called like a function. Because you need a thread-safe random-number generator, usingsrand
andrand
fromcstdlib
is a bad idea ... you should instead create some functor object that implements a thread-safe random-number generator, or a random-number generator that does not implement globally accessible variables so that everything remains thread-local storage.So for instance, one way this could work is you have some type of random number generator you've gotten from another library that will only generate random values between a fixed range of values so you can define the bounds of the container for the random-access iterators the
random_shuffle
algorithm uses. Now depending on what library you use, you functor could look something like the following:Now you can call the algorithm like:
and it will shuffle the vector in-between the start and end iterators to your vector without overflowing the bounds of the vector ... in other words it will only use values for the shuffle between
vector_start_index
andvector_end_index
.To use
rand_r
withstd::random_shuffle
, you'll need to write a (fairly trivial) wrapper. The random number generator you pass torandom_shuffle
needs to accept a parameter that specifies the range of numbers to be produced, whichrand_r
does not.Your wrapper would look something like this:
You'd use it with
random_shuffle
something like:Probably not.
Use the second version of adnrom_shuffle that takes a template parameter for the random number generator: http://www.sgi.com/tech/stl/random_shuffle.html. The generator must match: http://www.sgi.com/tech/stl/RandomNumberGenerator.html