Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Efficient way to fork processes and keep a running count?

by ikegami (Patriarch)
on Jan 28, 2010 at 06:13 UTC ( [id://820098]=note: print w/replies, xml ) Need Help??


in reply to Efficient way to fork processes and keep a running count?

A forking version:
use POSIX qw( _exit ); my $num_drives = 3; my $num_discs = 12; my @idle; # Idle drives my %busy; # Busy drives, keyed by the pid using them sub wait_for_a_kid { my $pid = wait(); if ($pid == -1) { warn("Can't wait: $!\n"); return 0; } ... check the child's exit code if desired ... push @idle, delete($busy{$pid}); return 1; } for my $drive (1..$num_drives) { ... eject disc ... push @idle, $drive; } my @queue = 1..$num_discs; while (@queue) { if (!@idle) { last if !wait_for_a_kid(); } my $disc = shift(@queue); my $drive = shift(@idle); my $pid = fork(); if (!defined($pid)) { warn("Can't fork: $!\n"); last; } if ($pid) { $busy{$pid} = $drive; next; } if (!eval { print("Please insert disc $disc in drive $drive\n"); ... wait for disc to be present ... ... read disc ... ... eject disc ... 1; }) { warn($@); _exit(1); } _exit(0); } while (keys(%busy)) { last if !wait_for_a_kid(); }

Update: Added some error checking. Fixed a bug exit wait loop.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://820098]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (4)
As of 2024-04-23 05:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found