Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Re: Need advice on how to fork with intercommunication

by NetWallah (Canon)
on Aug 05, 2007 at 14:46 UTC ( #630720=note: print w/replies, xml ) Need Help??

in reply to Need advice on how to fork with intercommunication

The THREAD code below should get you started.

Original attempt by me, but most credit goes to Browseruk.

#! perl -slw use strict; use threads; use Thread::Queue; $| = 1; #$OUTPUT_AUTOFLUSH our $KIDS ||= 10; our $WORK ||= 500; our $SLEEP||= 5; sub kid { my( $Q ) = shift; my $tid = threads->tid; my $count=0; printf "Kid: %02d started\n", $tid; ## Pick a work item of the queue and process it while( my $work = $Q->dequeue ) { printf "Kid: %02d processing work item '%s'\n", $tid, $work; $count ++; ## Replace the sleep with the code to process teh work items rand > 0.7 and sleep rand( $SLEEP ); } print "kid: $tid ending after processing $count items.\n"; } ## A queue for communications my $Q = new Thread::Queue; ## Start the kids my @kids = map{ threads->create( \&kid, $Q ) } 1 .. $KIDS; ## Wait till they're all up and running sleep 1 until @{[ threads->list ]} == $KIDS; ## Feed the queue with work ## The limit just ensure we don't fill lots of memory for my $workitem ( 1 .. $WORK ) { sleep 1 while $Q->pending > $KIDS *10; print "Queueing work item $workitem"; $Q->enqueue( $workitem ); } ## Tell them to stop $Q->enqueue( (undef) x $KIDS ); ## And wait for them to do so. $_->join for @kids;
This code has been posted to perlmonks a year or so ago, but I could not find the reference, and it was pretty short anyway.

     "An undefined problem has an infinite number of solutions." - Robert A. Humphrey         "If you're not part of the solution, you're part of the precipitate." - Henry J. Tillman

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (3)
As of 2022-08-17 15:50 GMT
Find Nodes?
    Voting Booth?

    No recent polls found