ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Coro/Coro/Channel.pm
Revision: 1.8
Committed: Sat Jul 21 18:21:45 2001 UTC (22 years, 10 months ago) by root
Branch: MAIN
Changes since 1.7: +14 -8 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.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 root 1.8 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 root 1.1 =over 4
24    
25     =cut
26    
27     package Coro::Channel;
28    
29 root 1.3 use Coro ();
30 root 1.1
31 root 1.8 $VERSION = 0.10;
32 root 1.1
33     =item $q = new Coro:Channel $maxsize
34    
35     Create a new channel with the given maximum size (unlimited if C<maxsize>
36 root 1.8 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 root 1.1
39     =cut
40    
41     sub new {
42 root 1.7 # [\@contents, [$getwait], $maxsize, [$putwait]];
43 root 1.8 bless [[], [], $_[1] || (1e30),[]], $_[0];
44 root 1.1 }
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 root 1.7
55 root 1.1 (pop @{$_[0][1]})->ready if @{$_[0][1]};
56 root 1.7
57 root 1.8 while (@{$_[0][0]} >= $_[0][2]) {
58     push @{$_[0][3]}, $Coro::current;
59     &Coro::schedule;
60 root 1.7 }
61 root 1.1 }
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 root 1.8 (pop @{$_[0][3]})->ready if @{$_[0][3]};
71    
72 root 1.1 while (!@{$_[0][0]}) {
73 root 1.3 push @{$_[0][1]}, $Coro::current;
74     &Coro::schedule;
75 root 1.1 }
76 root 1.7
77 root 1.1 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