Thread::Queue - Thread-safe queues
This document describes Thread::Queue version 3.14
use strict;
use warnings;
use threads;
use Thread::Queue;
my $q = Thread::Queue->new(); # A new empty queue
# Worker thread
my $thr = threads->create(
sub {
# Thread will loop until no more work
while (defined(my $item = $q->dequeue())) {
# Do work on $item
...
}
}
);
# Send work to the thread
$q->enqueue($item1, ...);
# Signal that there is no more work to be sent
$q->end();
# Join up with the thread when it finishes
$thr->join();
...
# Count of items in the queue
my $left = $q->pending();
# Non-blocking dequeue
if (defined(my $item = $q->dequeue_nb())) {
# Work on $item
}
# Blocking dequeue with 5-second timeout
if (defined(my $item = $q->dequeue_timed(5))) {
# Work on $item
}
# Set a size for a queue
$q->limit = 5;
# Get the second item in the queue without dequeuing anything
my $item = $q->peek(1);
# Insert two items into the queue just behind the head
$q->insert(1, $item1, $item2);
# Extract the last two items on the queue
my ($item1, $item2) = $q->extract(-2, 2);
This module provides thread-safe FIFO queues that can be accessed safely by any number of threads.
Any data types supported by threads::shared can be passed via queues:
Ordinary scalars are added to queues as they are.
If not already thread-shared, the other complex data types will be cloned (recursively, if needed, and including any bless
ings and read-only settings) into thread-shared structures before being placed onto a queue.
For example, the following would cause Thread::Queue to create a empty, shared array reference via &shared([])
, copy the elements 'foo', 'bar' and 'baz' from @ary
into it, and then place that shared reference onto the queue:
my @ary = qw/foo bar baz/;
$q->enqueue(\@ary);
However, for the following, the items are already shared, so their references are added directly to the queue, and no cloning takes place:
my @ary :shared = qw/foo bar baz/;
$q->enqueue(\@ary);
my $obj = &shared({});
$$obj{'foo'} = 'bar';
$$obj{'qux'} = 99;
bless($obj, 'My::Class');
$q->enqueue($obj);
See "LIMITATIONS" for caveats related to passing objects via queues.
Creates a new empty queue.
Creates a new queue pre-populated with the provided list of items.
The following methods deal with queues on a FIFO basis.