xref: /openbsd-src/gnu/usr.bin/perl/dist/Thread-Queue/examples/queue.pl (revision f2a19305cfc49ea4d1a5feb55cd6c283c6f1e031)
1#!/usr/bin/env perl
2
3use strict;
4use warnings;
5
6use threads;
7use Thread::Queue 3.01;
8
9# Create a work queue for sending data to a 'worker' thread
10#   Prepopulate it with a few work items
11my $work_q = Thread::Queue->new(qw/foo bar baz/);
12
13# Create a status queue to get reports from the thread
14my $status_q = Thread::Queue->new();
15
16# Create a detached thread to process items from the queue
17threads->create(sub {
18                    # Keep grabbing items off the work queue
19                    while (defined(my $item = $work_q->dequeue())) {
20                        # Process the item from the queue
21                        print("Thread got '$item'\n");
22
23                        # Ask for more work when the queue is empty
24                        if (! $work_q->pending()) {
25                            print("\nThread waiting for more work\n\n");
26                            $status_q->enqueue('more');
27                        }
28                    }
29
30                    # Final report
31                    print("Thread done\n");
32                    $status_q->enqueue('done');
33
34                })->detach();
35
36# More work for the thread
37my @work = (
38    [ 'bippity', 'boppity', 'boo' ],
39    [ 'ping', 'pong' ],
40    [ 'dit', 'dot', 'dit' ],
41);
42
43# Send work to the thread
44while ($status_q->dequeue() eq 'more') {
45    last if (! @work);   # No more work
46    $work_q->enqueue(@{shift(@work)});
47}
48
49# Signal that there is no more work
50$work_q->end();
51# Wait for thread to terminate
52$status_q->dequeue();
53# Good-bye
54print("Done\n");
55
56# EOF
57