c++ - 每个线程的 random_device 是否以不同的状态启动?

标签 c++ random

是否保证 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/

相关文章:

c++ - 运算符 >> 和 << 无法识别

python - cifar10 随机化训练和测试集

当天指定作者的 JavaScript 名言

python - PyTorch:如何从张量中采样,其中张量中的每个值都有不同的被选择可能性?

python - 如何直接复制 np.random 结果?

c++ - 漫反射 Material 奇怪的光线追踪行为

c++ - 数组声明和大小初始化(C++)

c++将一维数组与二维数据一起使用

C++ 可能在 COM 方法边界处抛出代码

algorithm - 如何平滑随机分布?