是random_shuffle线程安全吗?如果不是,使用rand_r [英] Is random_shuffle threadsafe? and using rand_r if it is not
问题描述
是std :: random_shuffle线程安全吗?我认为不是因为正常的rand()不是线程安全的。如果是这样,我如何使用rand_r与random_shuffle,以便我可以给每个线程一个唯一的种子。我已经看过使用random_shuffle自定义随机生成器的例子,但是对我来说还不清楚。
谢谢。
std :: random_shuffle
,您可以使用<需要写一个(相当微不足道的)包装器。传递给 random_shuffle
的随机数生成器需要接受指定要生成的数字范围的参数, rand_r
不会。 您的包装器看起来像这样:
class rand_x {
unsigned int seed;
public:
rand_x(int init):seed(init){}
int operator()(int limit){
int divisor = RAND_MAX / +1);
int retval;
do {
retval = rand_r(& seed)/ divisor;
} while(retval> limit);
return retval;
}
};
您可以使用 random_shuffle
例如:
std :: random_shuffle(whatever.begin(),whatever.end(),rand_x(some_seed));
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.
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));
这篇关于是random_shuffle线程安全吗?如果不是,使用rand_r的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!