In C++11, is the algorithm std::random_shuffle thread safe (when called by two different threads on two different containers) ?
And particularly this form:
template <class RandomIt> void random_shuffle(RandomIt first, RandomIt last);
In C++11, is the algorithm std::random_shuffle thread safe (when called by two different threads on two different containers) ?
And particularly this form:
template <class RandomIt> void random_shuffle(RandomIt first, RandomIt last);
A function is threadsafe if two concurrent executions of that function do not "work" on the same data. "work" here means that none of the functions may modify the data in a non-atomic, non-consistent way. There are three ways how data can be accessed by the function:
Since random_shuffle
is a free function, 2.
does not apply. The function however has parameters, and it works on them in the sense that it alters the underlying sequence's content. But there will be no problem if concurrent calls do not operate on overlapping sequences.
That leaves the static/global data. Most randum number generators will use some kind of global data for their seed. The default random function rand
is not required to be threadsafe and probably will not explicitly synchronize access to its global seed.
So in your case no, it's not threadsafe (unless the random number generator is).
You will want to either write a synchronized version of random number generator ore use different generators in concurrent calls. I'd prefer to use the latter, so the concurrent shuffles dont interfere with the random number sequence of each other. (But I am by no means an expert in random number generation).
It is thread-safe if it uses a thread-safe random number generator. The generator is implementation-defined (and, if it uses std::rand
, it's implementation-defined whether that is safe), so you'll need to consult the documentation for the implementation you're using.
To be sure, you should use one of the other variants, providing either a thread-safe generator, or a separate generator for each thread.