ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Coro/Coro/Channel.pm
Revision: 1.39
Committed: Mon Dec 12 17:49:07 2005 UTC (18 years, 5 months ago) by root
Branch: MAIN
Changes since 1.38: +1 -1 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 pcg 1.27 BEGIN { eval { require warnings } && warnings->unimport ("uninitialized") }
31 root 1.1
32 root 1.39 $VERSION = 1.51;
33 root 1.1
34     =item $q = new Coro:Channel $maxsize
35    
36     Create a new channel with the given maximum size (unlimited if C<maxsize>
37 root 1.8 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 root 1.1
40     =cut
41    
42     sub new {
43 root 1.7 # [\@contents, [$getwait], $maxsize, [$putwait]];
44 root 1.8 bless [[], [], $_[1] || (1e30),[]], $_[0];
45 root 1.1 }
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 root 1.7
56 root 1.1 (pop @{$_[0][1]})->ready if @{$_[0][1]};
57 root 1.7
58 root 1.8 while (@{$_[0][0]} >= $_[0][2]) {
59     push @{$_[0][3]}, $Coro::current;
60     &Coro::schedule;
61 root 1.7 }
62 root 1.1 }
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 root 1.8 (pop @{$_[0][3]})->ready if @{$_[0][3]};
72    
73 root 1.1 while (!@{$_[0][0]}) {
74 root 1.3 push @{$_[0][1]}, $Coro::current;
75     &Coro::schedule;
76 root 1.1 }
77 root 1.7
78 root 1.1 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 root 1.35 Marc Lehmann <schmorp@schmorp.de>
104 root 1.33 http://home.schmorp.de/
105 root 1.1
106     =cut
107