fork時のrand()の挙動

perlでforkしたときに、srand呼ばないと親プロセスとseedの値が同じになってしまうので、子プロセスの間でrand値が変わらなくてハマる、という経験があったのだけど、rubyの場合だとそのようなことはないようだ。

# perl
use strict;
use warnings;

warn rand();

for ( 1..10 ) {
    fork()
        or next;
    warn "$$: " . rand();

    exit;
}

wait() for (1..10);
# ruby
rand()

10.times do 
  Process.fork do
    p [$$, rand()]
  end
end
Process.waitall

実行結果はこのような感じ

$ perl hoge.pl
0.272763864210905 at hoge.pl line 4.
61802: 0.107602762381674 at hoge.pl line 9.
61803: 0.107602762381674 at hoge.pl line 9.
61804: 0.107602762381674 at hoge.pl line 9.
61805: 0.107602762381674 at hoge.pl line 9.
61806: 0.107602762381674 at hoge.pl line 9.
61808: 0.107602762381674 at hoge.pl line 9.
61810: 0.107602762381674 at hoge.pl line 9.
61811: 0.107602762381674 at hoge.pl line 9.
61812: 0.107602762381674 at hoge.pl line 9.
61813: 0.107602762381674 at hoge.pl line 9.

$ ruby hoge.rb
[62124, 0.20627116612114527]
[62125, 0.333383116761385]
[62126, 0.23762467129788523]
[62127, 0.14602078653671557]
[62128, 0.5977205787316395]
[62129, 0.4148314943310857]
[62130, 0.05280638343461841]
[62131, 0.008602114330672928]
[62132, 0.3500050758109612]
[62133, 0.6088914568482737]