Thread::Rand - repeatable random sequences between threads
This documentation describes version 0.07.
use Thread::Rand; # exports rand() and srand() use Thread::Rand (); # must call fully qualified subs BEGIN { Thread::Rand->global } # replace rand() and srand() globally
*** A note of CAUTION *** This module only functions on Perl versions 5.8.0 and later. And then only when threads are enabled with -Dusethreads. It is of no use with any version of Perl before 5.8.0 or without threads enabled. *************************
The Thread::Rand module allows you to create repeatable random sequences between different threads. Without it, repeatable random sequences can only be created within a thread.
There are only two subroutines.
my $value = rand(); # a value between 0 and 1 my $value = rand(number); # a value between 0 and number-1 inclusive
The "rand" subroutine functions exactly the same as the normal rand() function.
srand( usethis );
The "srand" subroutine functions exactly the same as the normal srand() function.
There is one class method.
use Thread::Rand (); BEGIN { Thread::Rand->global }
The "global" class method allows you to replace the rand() and srand() system functions in all programs by the version supplied by Thread::Rand. To ensure that the right subroutines are called, you must call this class method from within a BEGIN {} block.
load (any) Thread::Tie (0.09)
A bug in Perl 5.8.0 causes random sequences to be identical in threads if the rand() function was called in the parent thread. You can circumvent this problem by adding a CLONE subroutine thus:
sub CLONE { srand() } # needed for bug in 5.8.0
This will make sure that each thread gets its own unique seed and therefore its own unique sequence of random numbers. Alternately, you could also solve this with Thread::Rand and a call to the global class method thus:
You should however keep monitoring whether future versions of Perl will have this problem fixed. You can then take these circumventions out again.
Elizabeth Mattijsen, <liz@dijkmat.nl>.
Please report bugs to <perlbugs@dijkmat.nl>.
Copyright (c) 2002, 2003, 2012 Elizabeth Mattijsen <liz@dijkmat.nl>. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Thread::Tie.
To install Thread::Rand, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Thread::Rand
CPAN shell
perl -MCPAN -e shell install Thread::Rand
For more information on module installation, please visit the detailed CPAN module installation guide.