简体   繁体   English

默认构造的 std::random_device 不返回随机数

[英]Default constructed std::random_device doesn't return random number

I tried to run a simple example from cppreference about std::random_device , but on the line with function call d(rd1) program enters an infinite loop and never returns.我试图从cppreference中运行一个关于std::random_device的简单示例,但是在与 function 一致的情况下,调用d(rd1)程序进入无限循环并且永远不会返回。

Here is the code:这是代码:

#include <iostream>
#include <random>
 
int main()
{
 
    std::uniform_int_distribution<int> d(0, 10);
 
    std::random_device rd1;
    for(int n = 0; n < 10; ++n)
        std::cout << d(rd1) << ' ';
    std::cout << '\n';
}

After some inspections I found out that the function std::random_device::operator() always returns value 4294967295 which causes std::uniform_int_distribution<IntType>::operator() to enter an infinite loop.经过一些检查,我发现 function std::random_device::operator()总是返回值 4294967295 ,这导致std::uniform_int_distribution<IntType>::operator()进入无限循环。

If I explicitly call constructor with "rdrand" or "/dev/urandom" program works well, but with "rdseed" it's the same wrong result.如果我用"rdrand""/dev/urandom"程序显式调用构造函数效果很好,但使用"rdseed"它是相同的错误结果。 Also if I link against llvm's libc++ the example works normally.此外,如果我链接到 llvm 的 libc++,则该示例可以正常工作。 It is worth noting that on Ubuntu 16 and 18 it worked well but on Ubuntu 20 as well as Linux Mint 20 I experienced the issue.值得注意的是,在 Ubuntu 16 和 18 上运行良好,但在 Ubuntu 20 和 Linux 上,我遇到了问题

Why is the default constructed random device not working?为什么默认构造的随机设备不起作用?

uname -a output: unname uname -a output:

Linux my-pc 5.4.0-42-generic #46-Ubuntu SMP Fri Jul 10 00:24:02 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

and some more info about the system: lscpu , lshw以及有关系统的更多信息: lscpulshw

Why is the default constructed random device not working?为什么默认构造的随机设备不起作用?

Probably something to do with the quality of implementation, or a problem with the execution environment, or a combination of both.可能与实施质量有关,或与执行环境有关,或两者兼而有之。 This behaviour is certainly not guaranteed by the standard.标准当然不能保证这种行为。

In general, one probably shouldn't rely on randomness of std::random_device .一般来说,一个人可能不应该依赖std::random_device的随机性。 At least, combine it with another seed and / or a pseudo random number.至少,将它与另一个种子和/或伪随机数结合起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM