【发布时间】:2019-10-12 08:41:20
【问题描述】:
是否保证 random_device 不会在每个新线程的相同内部状态下启动?那么下面的代码有可能给出两个不同的值吗?
#include <iostream>
#include <random>
#include <thread>
#include <mutex>
using namespace std;
int main()
{
auto thr = []()
{
static mutex mtx;
mtx.lock();
cout << random_device()() << " " << endl;
mtx.unlock();
};
thread t1( thr );
thread t2( thr );
t1.join();
t2.join();
}
【问题讨论】:
-
不,我认为不能保证。
-
为什么你需要这个呢?您可以简单地预先创建多个 RNG 或重复使用 random_device 。
-
不,绝对与此无关。
-
@appleapple,random_device 是线程安全的,所以我可以这样做吗?我宁愿不相信这一点,因为这会使 random_device 的效率显着降低,即使没有争用因此没有内核等待。