gpt4 book ai didi

c++ - 替代 rand() 以避免竞争条件?

转载 作者:搜寻专家 更新时间:2023-10-30 23:52:51 25 4
gpt4 key购买 nike

根据:http://www.cplusplus.com/reference/cstdlib/rand/

In C, the generation algorithm used by rand is guaranteed to only be advanced by calls to this function. In C++, this constraint is relaxed, and a library implementation is allowed to advance the generator on other circumstances (such as calls to elements of ).

但是这里它说:

The function accesses and modifies internal state objects, which may cause data races with concurrent calls to rand or srand.

Some libraries provide an alternative function that explicitly avoids this kind of data race: rand_r (non-portable).

C++ library implementations are allowed to guarantee no data races for calling this function.

理想情况下,我希望有某种 rand 的“实例”,这样对于那个实例和给定的种子,我总是为调用 THAT instance 生成相同的数字序列。对于当前版本,似乎在某些平台中,其他函数对 rand() 的调用(甚至可能在不同线程上)可能会影响我的代码在我的线程中生成的数字序列。

是否有替代方案,我可以保留某种“实例”,保证在给定种子的情况下生成特定序列,并且对不同“实例”的其他调用不会影响它?

编辑:为清楚起见,我的代码将在多个不同的平台(iOS、Android、Windows 8.1、Windows 10、Linux 等)上运行,目前我不可能测试每个实现。我只想根据标准保证的内容来实现...

最佳答案

您可以使用 std::uniform_int_distributionstd::mt19937将生成器与您的公共(public)种子(全部来自 <random> 库)保持一致。

std::mt19937 gen(SEED);
std::uniform_int_distribution<> dis(MIN, MAX);
auto random_number = dis(gen);

在这里,SEED是您要指定的种子编号。您可以稍后使用 .seed 设置另一个种子方法也是:

std::mt19937 gen{};
gen.seed(SEED);

如果需要生成一个,可以使用std::random_device为此:

std::random_device rd{};
std::mt19937 gen(rd());

dis(MIN, MAX)部分设置了这个分布可以得出的最小值和最大值的范围,这意味着它永远不会产生大于 MAX 的值。 , 或小于 MIN .

最后,您可以使用带有此分布的生成器来生成您想要的随机值,如下所示:dis(gen) .该分布可以采用任何生成器,因此如果您想要其他具有相同随机数序列的分布,您可以复制 gen。 ,或使用相同的种子并构建两个或更多生成器。

关于c++ - 替代 rand() 以避免竞争条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43421215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com