dluxhu / perl-parallel-forkmanager

Parallel::ForkManager
20 stars 11 forks source link

Add srand to start method or add caveat to documentation? #22

Closed esabol closed 6 years ago

esabol commented 6 years ago

I recently came across this issue:

http://blogs.perl.org/users/brian_phillips/2010/06/when-rand-isnt-random.html

If you call rand in the parent process, then all your children will have the same random seed. For example:

> perl -MParallel::ForkManager -le 'rand; $PM = Parallel::ForkManager->new(2); for (1 .. 2) { $PM->start and next; print int rand 100; $PM->finish; }; $PM->wait_all_children;'

The workaround (or solution, if you prefer) is to do something like this:

$PM->run_on_start(sub { srand });
> perl -MParallel::ForkManager -le 'rand; $PM = Parallel::ForkManager->new(2); $PM->run_on_start(sub { srand }); for (1 .. 2) { $PM->start and next; print int rand 100; $PM->finish; }; $PM->wait_all_children;'

I think it would be a good idea to add a caveat for this issue to the documentation at least. You might want to even consider adding a call to srand in Parallel::ForkManager::start(). While there may be some unusual edge cases for which having all the children generate the same random numbers is useful, I can't believe that's very common.

yanick commented 6 years ago

Added to master,thanks!

esabol commented 6 years ago

A couple nitpicking comments added to https://github.com/dluxhu/perl-parallel-forkmanager/commit/2b1c51d593b8c38f948b37ae6f07d26e33ef0da2