- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
根据: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_distribution和 std::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/
假设我正在使用 APC,其中过程和调用代码都使用 SetLastError 和 GetLastError。这会导致 GetLastError 产生不可预测的值。有什么办法可以解决这个问题吗? VOID
关闭。这个问题是opinion-based .它目前不接受答案。 想改善这个问题吗?更新问题,以便可以通过 editing this post 用事实和引文回答问题. 7年前关闭。 Improve t
任何人都可以,请告诉我,如何在不进行JavaScript轮询/ setInterval的情况下,在完整日历上填充/显示在服务器端动态更新的数据。 grails中提供了Atmosphere插件,但是文档
我正在尝试调整我的代码,从仅在前台使用 WCSessionDelegate 回调到在后台通过 handleBackgroundTasks: 接受 WKWatchConnectivityRefreshB
我正在构建批处理系统。 单位 的批处理数量从 20 到 1000 不等。每个 Unit 本质上都是模型的层次结构(一个主模型和许多子模型)。我的任务涉及将每个模型层次结构作为单个事务保存到数据库中(每
我拍了一张图片并将其切成三 block ,然后将它们向右浮动,让文字围绕它们流动。 HTML 看起来像这样: 在我添加侧边栏并将其 float 到图像的右上方之前,它工作正常,就像这样... T
我正在考虑嵌入式 Linux 项目(还没有硬件)中即将出现的情况,其中两个外部芯片需要共享一条物理 IRQ 线。这条线在硬件中能够实现边沿触发,但不能实现电平触发中断。 查看 Linux 中的共享 i
我观察到,当 linux futexes 发生争用时,系统会在自旋锁上花费大量时间。我注意到即使不直接使用 futex 也是一个问题,但在调用 malloc/free、rand、glib 互斥调用和其
我终于能够获得一些工具提示,最终可以使用以下代码: Hover over me 然后 $('[rel=tooltip]').tooltip(); 我遇到的问题是它使用 jQueryUI 工
我是一名优秀的程序员,十分优秀!