【问题标题】:Why don't child processes produce the same random number if you don't set the seed?如果不设置种子,为什么子进程不产生相同的随机数?
【发布时间】:2016-12-09 18:48:57
【问题描述】:

srand 的文档中,它说:

另一种情况是,您可能希望在“fork”之后调用“srand”,以避免子进程与父进程共享相同的种子值(因此彼此共享)。

我可以发誓我从来没有遇到过这个,所以我测试了它:

$ perl -E 'for (1 .. 8) { next if fork; say rand; exit;} wait for 1 .. 8'
0.301967407417582
0.497966311014356
0.05798998109913
0.907357103963481
0.240495550287054
0.74279685605234
0.368774714022042
0.562179033951001

然后我用srand 测试在父节点中设置种子:

$ perl -E 'srand; for (1 .. 8) { next if fork; say rand; exit;} wait for 1 .. 8'
0.13028028358622
0.13028028358622
0.13028028358622
0.13028028358622
0.13028028358622
0.13028028358622
0.13028028358622
0.13028028358622

因此,如果您在父项中设置种子,则子项都将获得相同的值。为什么在第一个示例中没有发生这种情况?

【问题讨论】:

    标签: perl seed srand


    【解决方案1】:

    诀窍在于种子被设置的时候。 perl 启动时未设置;它在首次调用 rand 时被设置。在第一种情况下,首先在每个孩子中调用rand,因此每个孩子都有自己的种子。如果您在父级中调用rand,您可以看到这一点:

    $ perl -E 'say "parent: ", rand; for (1 .. 8) { next if fork; say "$$: ", rand; exit;} wait for 1 .. 8'
    parent: 0.931186094953777
    60700: 0.105917756769003
    60701: 0.105917756769003
    60702: 0.105917756769003
    60703: 0.105917756769003
    60704: 0.105917756769003
    60705: 0.105917756769003
    60706: 0.105917756769003
    60707: 0.105917756769003
    

    所以,如果您需要确定孩子有不同的随机种子,他们需要在启动时调用srand(因为您永远不知道父级中可能调用srandrand 的代码)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-02
      • 2018-06-04
      • 1970-01-01
      • 2015-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多