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.
rand_r is thread safe is because the function is entirely pure. It doesn't read or modify any state other than the arguments. It can therefore be safely called concurrently.
The function rand() is not reentrant or thread-safe, since it uses hidden state that is modified on each call.
rand(), rand_r() — Generate Random Number Threadsafe: No. 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.
To use rand_r
with std::random_shuffle
, you'll need to write a (fairly trivial) wrapper. The random number generator you pass to random_shuffle
needs to accept a parameter that specifies the range of numbers to be produced, which rand_r
does not.
Your wrapper would look something like this:
class rand_x {
unsigned int seed;
public:
rand_x(int init) : seed(init) {}
int operator()(int limit) {
int divisor = RAND_MAX/(limit+1);
int retval;
do {
retval = rand_r(&seed) / divisor;
} while (retval > limit);
return retval;
}
};
You'd use it with random_shuffle
something like:
std::random_shuffle(whatever.begin(), whatever.end(), rand_x(some_seed));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With