c++ - Is std::random_shuffle thread safe? -
this question has answer here:
in c++11, algorithm std::random_shuffle thread safe (when called 2 different threads on 2 different containers) ?
and particularly form:
template <class randomit> void random_shuffle(randomit first, randomit last);
a function threadsafe if 2 concurrent executions of function not "work" on same data. "work" here means none of functions may modify data in non-atomic, non-consistent way. there 3 ways how data can accessed function:
- via function parameters, including objects referred parameters
- via objects member function called on
- function static, class static , global data, including data used functions called indirectly.
since random_shuffle
free function, 2.
not apply. function has parameters, , works on them in sense alters underlying sequence's content. there no problem if concurrent calls not operate on overlapping sequences.
that leaves static/global data. randum number generators use kind of global data seed. default random function rand
not required threadsafe , not explicitly synchronize access global seed.
so in case no, it's not threadsafe (unless random number generator is).
you want either write synchronized version of random number generator ore use different generators in concurrent calls. i'd prefer use latter, concurrent shuffles dont interfere random number sequence of each other. (but no means expert in random number generation).
Comments
Post a Comment