1 |
=head1 NAME |
2 |
|
3 |
Coro::Channel - message queues |
4 |
|
5 |
=head1 SYNOPSIS |
6 |
|
7 |
use Coro::Channel; |
8 |
|
9 |
$q1 = new Coro::Channel <maxsize>; |
10 |
|
11 |
$q1->put("xxx"); |
12 |
print $q1->get; |
13 |
|
14 |
die unless $q1->size; |
15 |
|
16 |
=head1 DESCRIPTION |
17 |
|
18 |
A Coro::Channel is the equivalent of a pipe: you can put things into it on |
19 |
one end end read things out of it from the other hand. If the capacity of |
20 |
the Channel is maxed out writers will block. Both ends of a Channel can be |
21 |
read/written from as many coroutines as you want. |
22 |
|
23 |
=over 4 |
24 |
|
25 |
=cut |
26 |
|
27 |
package Coro::Channel; |
28 |
|
29 |
use Coro (); |
30 |
BEGIN { eval { require warnings } && warnings->unimport ("uninitialized") } |
31 |
|
32 |
$VERSION = 1.9; |
33 |
|
34 |
=item $q = new Coro:Channel $maxsize |
35 |
|
36 |
Create a new channel with the given maximum size (unlimited if C<maxsize> |
37 |
is omitted). Giving a size of one gives you a traditional channel, i.e. a |
38 |
queue that can store only a single element. |
39 |
|
40 |
=cut |
41 |
|
42 |
sub new { |
43 |
# [\@contents, [$getwait], $maxsize, [$putwait]]; |
44 |
bless [[], [], $_[1] || (1e30),[]], $_[0]; |
45 |
} |
46 |
|
47 |
=item $q->put($scalar) |
48 |
|
49 |
Put the given scalar into the queue. |
50 |
|
51 |
=cut |
52 |
|
53 |
sub put { |
54 |
push @{$_[0][0]}, $_[1]; |
55 |
|
56 |
(pop @{$_[0][1]})->ready if @{$_[0][1]}; |
57 |
|
58 |
while (@{$_[0][0]} >= $_[0][2]) { |
59 |
push @{$_[0][3]}, $Coro::current; |
60 |
&Coro::schedule; |
61 |
} |
62 |
} |
63 |
|
64 |
=item $q->get |
65 |
|
66 |
Return the next element from the queue, waiting if necessary. |
67 |
|
68 |
=cut |
69 |
|
70 |
sub get { |
71 |
(pop @{$_[0][3]})->ready if @{$_[0][3]}; |
72 |
|
73 |
while (!@{$_[0][0]}) { |
74 |
push @{$_[0][1]}, $Coro::current; |
75 |
&Coro::schedule; |
76 |
} |
77 |
|
78 |
shift @{$_[0][0]}; |
79 |
} |
80 |
|
81 |
=item $q->size |
82 |
|
83 |
Return the number of elements waiting to be consumed. Please note that: |
84 |
|
85 |
if ($q->size) { |
86 |
my $data = $q->get; |
87 |
} |
88 |
|
89 |
is NOT a race condition but works fine. |
90 |
|
91 |
=cut |
92 |
|
93 |
sub size { |
94 |
scalar @{$_[0][0]}; |
95 |
} |
96 |
|
97 |
1; |
98 |
|
99 |
=back |
100 |
|
101 |
=head1 AUTHOR |
102 |
|
103 |
Marc Lehmann <schmorp@schmorp.de> |
104 |
http://home.schmorp.de/ |
105 |
|
106 |
=cut |
107 |
|