Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is random_shuffle threadsafe? and using rand_r if it is not

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.

like image 734
Mark Avatar asked Jul 05 '11 19:07

Mark


People also ask

Is Rand_r thread safe?

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.

Why is rand not thread safe C?

The function rand() is not reentrant or thread-safe, since it uses hidden state that is modified on each call.

Is rand thread safe c++?

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.


1 Answers

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));
like image 115
Jerry Coffin Avatar answered Sep 22 '22 16:09

Jerry Coffin