steflama has asked for the wisdom of the Perl Monks concerning the following question:

Hello! I'm faced with a problem, i have an array of 20 elements ("fruits"), my task is to start a maximum number of 5 children where each will pick one of the fruits array element and in that child sleep for a random number of seconds (between 3-10secods) the trick is that beeing limited on a 5max childs perl sould wait for any child to end and start another one but keep to max 5 chils and run until all elements of fruits array get a nice "sleep" Can anyone help? I'm all out of ideas on this one, an no code i've tried to come up with does any job and they do not worth showing here ... :( THANKS!

Replies are listed 'Best First'.
Re: Parallel::ForkManager loop in array
by choroba (Cardinal) on Aug 17, 2016 at 22:53 UTC
    > I'm all out of ideas

    Have you read the documentation of Parallel::ForkManager? Can you share the code that didn't work?

    Update: Copied from the documentation, fruits, sleep, and srand added by me:

    #!/usr/bin/perl use warnings; use strict; use Parallel::ForkManager; my $pm = Parallel::ForkManager->new(5); for my $fruit (qw( apple banana cherry lemon lime orange peach pear plum raspberry strawberry )) { my $pid = $pm->start and next; print "Sleeping with $fruit\n"; srand; # To prevent all the children from having the same seed. sleep 3 + rand 8; print "$fruit done.\n"; $pm->finish } $pm->wait_all_children;

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

      In the spirit of TIMTOWDI, the following snippet demonstrates another way. Calling srand is not necessary as the seed is already unique per worker.

      #!/usr/bin/perl use warnings; use strict; use MCE::Loop chunk_size => 1, max_workers => 5; my @fruits = qw( apple banana cherry lemon lime orange peach pear plum raspberry strawberry ); mce_loop { my $fruit = $_; print "Sleeping with $fruit\n"; sleep 3 + rand 8; print "$fruit done.\n"; } \@fruits; MCE::Loop->finish;

      Regards, Mario.

Re: Parallel::ForkManager loop in array
by Anonymous Monk on Aug 17, 2016 at 23:10 UTC
    #!/usr/bin/perl # http://perlmonks.org/?node_id=1169958 use Time::HiRes 'sleep'; use strict; use warnings; my @fruits = 'fruit001' .. 'fruit020'; my $max = 5; my $active = 0; while(my $fruit = shift @fruits ) { while( $active >= $max ) { wait; $active--; } if( my $pid = fork ) { $active++ } elsif( defined $pid ) { sleep 3 + rand 7; print "completed $fruit\n"; exit; } else { die "fork failed $!"; } } 1 while wait > 0;
Re: Parallel::ForkManager loop in array
by steflama (Initiate) on Aug 18, 2016 at 00:40 UTC
    Thank you both! I've managed to get the desired result from both your wisdom :) I will get back and share my version. Thanks again!