in reply to Is this a job for a fork?

As BrowserUk said, threads may be an easier choice. I noodled around with this before I saw his reply and came up with this adaptation of your script.

#!/usr/bin/perl use warnings; use strict; use Data::Dumper; use threads; use threads::shared; my %count : shared; my $maxthreads = 3; # there are way more lines than this but anyway... for my $i ( 1 .. 500 ) { redo if ( scalar threads->list() >= $maxthreads ); # this just represents that I've found a pair and want to run the +sub if ( $i % 50 == 0 ) { # run the sub my $thread = threads->new( \&inc, $i, 2 ); } } while ( scalar threads->list() ) { sleep 1 } # I need access to the hash that's updated in the sub print Dumper \%count; sub inc { my ( $param1, $param2 ) = @_; #long subroutine using passed params # pausing for effect! # this simulates that the sub takes a while to run sleep( 5 + ( rand 5 ) ); # let you know something is happening print "$param1\n"; # make a change to the hash $count{$param1} = $param1 * $param2; threads->self()->detach; }

Replies are listed 'Best First'.
Re^2: Is this a job for a fork?
by richardwfrancis (Beadle) on Jul 13, 2010 at 09:14 UTC

    This is exactly what I'm looking for thundergnat. Awesome thank you!!!

    Many thanks also to BrowserUk for his threads solution too.

    This work is actually part of some software I'm hoping to publish in a scientific journal so I'll be sure to acknowledge you both.

    Also thanks to JavaFan for the fork pseudocode and thomas11 for his suggestion too

    This site has never failed me. The monks have been taking their genius pills. Good monks.

    Cheers

    Rich

      Be aware. Whilst thundergnat's solution works, creating a new thread for every pairing is expensive (assuming there will be thousands of pairings). The Queue solution avoids this by re-using the threads


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.

        OK. Thank you BrowserUK. I think that once I've familiarised myself with threads my eventual solution will be a combo of yours and thundergnat's so I'll definitely keep this in mind.

        Many thanks again