Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Thread communication

by jbert (Priest)
on Aug 27, 2008 at 15:36 UTC ( #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"; }


Comment on Re: Thread communication
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (13)
As of 2015-07-31 11:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (276 votes), past polls