Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Thread communication

by jbert (Priest)
on Aug 27, 2008 at 15:36 UTC ( [id://707188]=note: print w/replies, xml ) Need Help??


in reply to Thread communication

Here's some working queuer/consumer code based on Thread::Queue. Hope it helps.~
#!/usr/bin/perl use threads; use threads::shared; use Thread::Queue; my $q : shared; use constant FINISH => 'finish'; main(); exit 0; sub main { $q = Thread::Queue->new(); my $queuer = threads->create('queuer', 10); my $worker = threads->create('worker'); $queuer->join; $worker->join; print "main thread finished\n"; } sub queuer { my $numItems = shift; my $str = "foo"; while ($numItems-- > 0) { print "queueing $str\n"; $q->enqueue($str); $str++; sleep 1; } $q->enqueue(FINISH); print "queuer finished\n"; } sub worker { DOING_WORK: while (1) { while (my $pending = $q->pending) { my $str = $q->dequeue; print "worker found $pending items, got $str\n"; last DOING_WORK if $str eq FINISH; } sleep 3; } print "worker finished\n"; }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2024-03-28 16:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found