use strict;
use warnings;
use 5.012;
use threads;
use Thread::Queue;
my $q = Thread::Queue->new;
sub do_stuff {
my $id = threads->tid;
my $data;
while ($data = $q->dequeue) {
#Process data:
sleep rand(5);
say "$id: Done with: '$data'. ",
'Going back to q to get more data.';
}
say "$id: No more data in q. Quitting...";
}
my $max_threads = 5;
my @threads = map { threads->create(\&do_stuff) }
1 .. $max_threads
;
#All threads are now blocking on dequeue() and waiting for data.
my @data = qw(
hi hello greetings
what where how
world earth gia
mars venus jupiter
);
for my $data (@data) {
$q->enqueue($data);
}
#Make all threads exit their while loops:
for (1 .. $max_threads) {
$q->enqueue(undef);
}
#Don't end the program until all threads have finished:
for my $thr (@threads) {
$thr->join
}
--output:--
1: Done with: 'greetings'. Going back to q to get more data.
5: Done with: 'hello'. Going back to q to get more data.
3: Done with: 'what'. Going back to q to get more data.
5: Done with: 'world'. Going back to q to get more data.
5: Done with: 'earth'. Going back to q to get more data.
4: Done with: 'how'. Going back to q to get more data.
2: Done with: 'hi'. Going back to q to get more data.
1: Done with: 'where'. Going back to q to get more data.
1: No more data in q. Quitting...
5: Done with: 'mars'. Going back to q to get more data.
5: No more data in q. Quitting...
3: Done with: 'gia'. Going back to q to get more data.
3: No more data in q. Quitting...
4: Done with: 'venus'. Going back to q to get more data.
4: No more data in q. Quitting...
2: Done with: 'jupiter'. Going back to q to get more data.
2: No more data in q. Quitting...