是否保证 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();
}
最佳答案
没有这样的保证。
在 cppreference 上我们可以读取
std::random_device may be implemented in terms of an implementation-defined pseudo-random number engine if a non-deterministic source (e.g. a hardware device) is not available to the implementation. In this case each std::random_device object may generate the same number sequence.
这基本上取决于实现。
另一件事是创建新的 random_device
会产生性能成本。最好重复使用同一个。
auto thr = []()
{
static mutex mtx;
static random_device rd{};
mtx.lock();
cout << rd() << " " << endl;
mtx.unlock();
};
关于c++ - 每个线程的 random_device 是否以不同的状态启动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58352384/