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 |
=over 4 |
19 |
|
20 |
=cut |
21 |
|
22 |
package Coro::Channel; |
23 |
|
24 |
use Coro::Process (); |
25 |
|
26 |
$VERSION = 0.01; |
27 |
|
28 |
=item $q = new Coro:Channel $maxsize |
29 |
|
30 |
Create a new channel with the given maximum size (unlimited if C<maxsize> |
31 |
is omitted). Stating a size of zero gives you a traditional channel, i.e. |
32 |
a queue that can store only a single element. |
33 |
|
34 |
=cut |
35 |
|
36 |
sub new { |
37 |
# [\@contents, $queue, $maxsize]; |
38 |
bless [[], [], $_[1]], $_[0]; |
39 |
} |
40 |
|
41 |
=item $q->put($scalar) |
42 |
|
43 |
Put the given scalar into the queue. |
44 |
|
45 |
=cut |
46 |
|
47 |
sub put { |
48 |
push @{$_[0][0]}, $_[1]; |
49 |
(pop @{$_[0][1]})->ready if @{$_[0][1]}; |
50 |
&Coro::Process::yield if defined $_[0][2] && @{$_[0][0]} > $_[0][2]; |
51 |
} |
52 |
|
53 |
=item $q->get |
54 |
|
55 |
Return the next element from the queue, waiting if necessary. |
56 |
|
57 |
=cut |
58 |
|
59 |
sub get { |
60 |
while (!@{$_[0][0]}) { |
61 |
push @{$_[0][1]}, $Coro::Process::current; |
62 |
&Coro::Process::schedule; |
63 |
} |
64 |
shift @{$_[0][0]}; |
65 |
} |
66 |
|
67 |
=item $q->size |
68 |
|
69 |
Return the number of elements waiting to be consumed. Please note that: |
70 |
|
71 |
if ($q->size) { |
72 |
my $data = $q->get; |
73 |
} |
74 |
|
75 |
is NOT a race condition but works fine. |
76 |
|
77 |
=cut |
78 |
|
79 |
sub size { |
80 |
scalar @{$_[0][0]}; |
81 |
} |
82 |
|
83 |
1; |
84 |
|
85 |
=back |
86 |
|
87 |
=head1 AUTHOR |
88 |
|
89 |
Marc Lehmann <pcg@goof.com> |
90 |
http://www.goof.com/pcg/marc/ |
91 |
|
92 |
=cut |
93 |
|