What is a thread-safe random number generator for perl?

£可爱£侵袭症+ 提交于 2020-01-16 11:50:11

问题


The core perl function rand() is not thread-safe, and I need random numbers in a threaded monte carlo simulation.

I'm having trouble finding any notes in CPAN on the various random-number generators there as to which (if any) are thread-safe, and every google search I do keeps getting cluttered with C/C++/python/anything but perl. Any suggestions?


回答1:


Do not use built-in rand for Monte Carlo on Windows. At least, try:

my %r = map { rand() => undef } 1 .. 1_000_000;
print scalar keys %r, "\n";

If nothing has changed, it should print 32768 which is utterly unsuitable for any kind of serious work. And, even if it does print a larger number, you're better off sticking with a PRNG with known good qualities for simulation.

You can use Math::Random::MT.

You can instantiate a new Math::Random::MT object in each thread with its own array of seeds. Mersenne Twister has good properties for simulation.




回答2:


Do you have /dev/urandom on your system?

BEGIN {
    open URANDOM, '<', '/dev/urandom';
}

sub urand {  # drop in replacement for rand.
    my $expr = shift || 1;
    my $x;
    read URANDOM, $x, 4;
    return $expr * unpack("I", $x) / (2**32);
}



回答3:


rand is thread safe, and I think you got the wrong definition of what "thread safe" means, If its not "thread safe" It means the program/function is modifying its "shared" data structure that makes its execution in thread mode unsafe.

Check Rand function documentation, Notice it take EXPR as argument, in every thread you can provide a different EXPR.

http://perldoc.perl.org/functions/rand.html



来源:https://stackoverflow.com/questions/15574374/what-is-a-thread-safe-random-number-generator-for-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!