Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

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"; }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://707188]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2017-07-29 12:09 GMT
Find Nodes?
    Voting Booth?
    I came, I saw, I ...

    Results (435 votes). Check out past polls.