ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Coro/Coro/Channel.pm
Revision: 1.13
Committed: Sun Sep 16 01:34:36 2001 UTC (22 years, 8 months ago) by root
Branch: MAIN
Changes since 1.12: +1 -1 lines
Log Message:
*** empty log message ***

File Contents

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