每个线程的random_device是否以不同的状态开始?

问题描述 投票:2回答:1

是否可以确保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();
}
c++ random
1个回答
0
投票

没有这样的保证。

关于cppreference,我们可以阅读

如果不确定性源(例如硬件设备)不可用于实现,则可以根据实现定义的伪随机数引擎来实现

std :: random_device。在这种情况下,每个std :: random_device对象都可以生成相同的数字序列。

基本上取决于实现。

另一件事是创建新的random_device会降低性能。最好重用相同的一个。

auto thr = []()
{
    static mutex mtx;
    static random_device rd{};
    mtx.lock();
    cout << rd() << " " << endl;
    mtx.unlock();
};
© www.soinside.com 2019 - 2024. All rights reserved.