File Coverage

blib/lib/AnyEvent/Loop.pm
Criterion Covered Total %
statement 86 115 74.7
branch 28 40 70.0
condition 17 32 53.1
subroutine 14 18 77.7
pod 3 7 42.8
total 148 212 69.8


line stmt bran cond sub pod time code
1             =head1 NAME
2              
3             AnyEvent::Loop - AnyEvent's Pure-Perl event loop
4              
5             =head1 SYNOPSIS
6              
7             use AnyEvent;
8             # use AnyEvent::Loop;
9            
10             # this module gets loaded automatically when no other loop can be found
11              
12             # Explicit use:
13             use AnyEvent::Loop;
14             use AnyEvent;
15              
16             ...
17              
18             AnyEvent::Loop::run; # run the event loop
19              
20             =head1 DESCRIPTION
21              
22             This module provides an event loop for AnyEvent in case no other event
23             loop could be found or loaded. You don't have to do anything to make it
24             work with AnyEvent except by possibly loading it before creating the first
25             AnyEvent watcher.
26              
27             This module is I<not> some loop abstracion used by AnyEvent, but just
28             another event loop like EV or Glib, just written in pure perl and
29             delivered with AnyEvent, so AnyEvent always works, even in the absence of
30             any other backend.
31              
32             If you want to use this module instead of autoloading a potentially better
33             event loop you can simply load it (and no other event loops) before
34             creating the first watcher.
35              
36             As for performance, this module is on par with (and usually faster than)
37             most select/poll-based C event modules such as Event or Glib (it does not
38             even come close to EV, though), with respect to I/O watchers. Timers are
39             handled less optimally, but for many common tasks, it is still on par with
40             event loops written in C.
41              
42             This event loop has been optimised for the following use cases:
43              
44             =over 4
45              
46             =item monotonic clock is available
47              
48             This module will use the POSIX monotonic clock option (if it can be
49             detected at runtime) or the POSIX C<times> function (if the resolution
50             is at least 100Hz), in which case it will not suffer adversely from time
51             jumps.
52              
53             If no monotonic clock is available, this module will not attempt to
54             correct for time jumps in any way.
55              
56             The clock chosen will be reported if the environment variable
57             C<$PERL_ANYEVENT_VERBOSE> is set to 8 or higher.
58              
59             =item any number of watchers on one fd
60              
61             Supporting a large number of watchers per fd is purely a dirty benchmark
62             optimisation not relevant in practise. The more common case of having one
63             watcher per fd/poll combo is special-cased, however, and therefore fast,
64             too.
65              
66             =item relatively few active fds per C<select> call
67              
68             This module expects that only a tiny amount of fds is active at any one
69             time. This is relatively typical of larger servers (but not the case where
70             C<select> traditionally is fast), at the expense of the "dense activity
71             case" where most of the fds are active (which suits C<select>).
72              
73             The optimal implementation of the "dense" case is not much faster, though,
74             so the module should behave very well in most cases, subject to the bad
75             scalability of C<select> in the presence of a large number of inactive
76             file descriptors.
77              
78             =item lots of timer changes/iteration, or none at all
79              
80             This module sorts the timer list using perl's C<sort>, even though a total
81             ordering is not required for timers internally.
82              
83             This sorting is expensive, but means sorting can be avoided unless the
84             timer list has changed in a way that requires a new sort.
85              
86             This means that adding lots of timers is very efficient, as well as not
87             changing the timers. Advancing timers (e.g. recreating a timeout watcher
88             on activity) is also relatively efficient, for example, if you have a
89             large number of timeout watchers that time out after 10 seconds, then the
90             timer list will be sorted only once every 10 seconds.
91              
92             This should not have much of an impact unless you have hundreds or
93             thousands of timers, though, or your timers have very small timeouts.
94              
95             =back
96              
97             =head1 FUNCTIONS
98              
99             The only user-visible functions provided by this module loop related -
100             watchers are created via the normal AnyEvent mechanisms.
101              
102             =over 4
103              
104             =item AnyEvent::Loop::run
105              
106             Run the event loop, usually the last thing done in the main program when
107             you want to use the pure-perl backend.
108              
109             =item AnyEvent::Loop::one_event
110              
111             Blocks until at least one new event has been received by the operating
112             system, whether or not it was AnyEvent-related.
113              
114             =back
115              
116             =cut
117              
118             package AnyEvent::Loop;
119              
120 14     14   904 use Scalar::Util qw(weaken);
  14         21  
  14         1330  
121 14     14   73 use List::Util ();
  14         19  
  14         161  
122              
123 14     14   48 use AnyEvent (); BEGIN { AnyEvent::common_sense }
  14     14   26  
  14         248  
  14         63  
124 14     14   5233 use AnyEvent::Util ();
  14         29  
  14         5385  
125              
126             our $VERSION = $AnyEvent::VERSION;
127              
128             our ($NOW, $MNOW);
129              
130             sub MAXWAIT() { 3600 } # never sleep for longer than this many seconds
131              
132             BEGIN {
133 14     14   78 local $SIG{__DIE__}; # protect us against the many broken __DIE__ handlers out there
134 14     14   886 my $time_hires = eval "use Time::HiRes (); 1";
  14         6338  
  14         17123  
  14         132  
135 14     14   645 my $clk_tck = eval "use POSIX (); POSIX::sysconf (POSIX::_SC_CLK_TCK ())";
  14         6596  
  14         93500  
  14         286  
136 14         34 my $round; # actual granularity
137              
138 14 50 33     603 if ($time_hires && eval "&Time::HiRes::clock_gettime (Time::HiRes::CLOCK_MONOTONIC ())") {
    0 0        
    0 0        
139 14         535 AE::log 8 => "Using CLOCK_MONOTONIC as timebase.";
140             *_update_clock = sub {
141 179     179   519 $NOW = &Time::HiRes::time;
142 179         915 $MNOW = Time::HiRes::clock_gettime (&Time::HiRes::CLOCK_MONOTONIC);
143 14         63 };
144              
145 0         0 } elsif (100 <= $clk_tck && $clk_tck <= 1000000 && eval { (POSIX::times ())[0] != -1 }) { # -1 is also a valid return value :/
146 0         0 AE::log 8 => "Using POSIX::times (monotonic) as timebase.";
147 0         0 my $HZ1 = 1 / $clk_tck;
148              
149 0         0 my $last = (POSIX::times ())[0];
150 0         0 my $next;
151             *_update_clock = sub {
152 0         0 $NOW = time; # d'oh
153              
154 0         0 $next = (POSIX::times ())[0];
155             # we assume 32 bit signed on wrap but 64 bit will never wrap
156 0 0       0 $last -= 4294967296 if $last > $next; # 0x100000000, but perl has problems with big hex constants
157 0         0 $MNOW += ($next - $last) * $HZ1;
158 0         0 $last = $next;
159 0         0 };
160              
161 0         0 $round = $HZ1;
162              
163             } elsif (eval "use Time::HiRes (); 1") {
164 0         0 AE::log 8 => "Using Time::HiRes::time (non-monotonic) clock as timebase.";
165             *_update_clock = sub {
166 0         0 $NOW = $MNOW = &Time::HiRes::time;
167 0         0 };
168              
169             } else {
170 0         0 AE::log fatal => "Unable to find sub-second time source (is this really perl 5.8.0 or later?)";
171             }
172              
173 14 50       84 $round = 0.001 if $round < 0.001; # 1ms is enough for us
174 14         39 $round -= $round * 1e-2; # 0.1 => 0.099
175 14         13143 eval "sub ROUNDUP() { $round }";
176             }
177              
178             _update_clock;
179              
180             # rely on AnyEvent:Base::time to provide time
181 37     37 0 100 sub now () { $NOW }
182 0     0 0 0 sub now_update() { _update_clock }
183              
184             # fds[0] is for read, fds[1] is for write watchers
185             # fds[poll][V] is the bitmask for select
186             # fds[poll][W][fd] contains a list of i/o watchers
187             # an I/O watcher is a blessed arrayref containing [fh, poll(0/1), callback, queue-index]
188             # the queue-index is simply the index in the [W] array, which is only used to improve
189             # benchmark results in the synthetic "many watchers on one fd" benchmark.
190             my @fds = ([], []);
191             sub V() { 0 }
192             sub W() { 1 }
193              
194             my $need_sort = 1e300; # when to re-sort timer list
195             my @timer; # list of [ abs-timeout, Timer::[callback] ]
196             my @idle; # list of idle callbacks
197              
198             # the pure perl mainloop
199             sub one_event {
200 96     96 1 368 _update_clock;
201              
202             # first sort timers if required (slow)
203 96 100       770 if ($MNOW >= $need_sort) {
204 16         31 $need_sort = 1e300;
205 16         63 @timer = sort { $a->[0] <=> $b->[0] } @timer;
  9         100  
206             }
207              
208             # handle all pending timers
209 96 100 100     523 if (@timer && $timer[0][0] <= $MNOW) {
210 27   100     65 do {
211 28         93 my $timer = shift @timer;
212 28 100       244 $timer->[1] && $timer->[1]($timer);
213             } while @timer && $timer[0][0] <= $MNOW;
214              
215             } else {
216             # poll for I/O events, we do not do this when there
217             # were any pending timers to ensure that one_event returns
218             # quickly when some timers have been handled
219 69 100 100     381 my ($wait, @vec, $fds)
220             = (@timer && $timer[0][0] < $need_sort ? $timer[0][0] : $need_sort) - $MNOW;
221              
222 69 100       178 $wait = $wait < MAXWAIT ? $wait + ROUNDUP : MAXWAIT;
223 69 50       138 $wait = 0 if @idle;
224              
225 69         1382815 $fds = CORE::select
226             $vec[0] = $fds[0][V],
227             $vec[1] = $fds[1][V],
228             AnyEvent::WIN32 ? $vec[2] = $fds[1][V] : undef,
229             $wait;
230              
231 69         1036 _update_clock;
232              
233 69 100 66     1031 if ($fds > 0) {
    100 66        
234             # buggy microshit windows errornously sets exceptfds instead of writefds
235 48         58 $vec[1] |= $vec[2] if AnyEvent::WIN32;
236              
237             # prefer write watchers, because they might reduce memory pressure.
238 48         105 for (1, 0) {
239 96         195 my $fds = $fds[$_];
240              
241             # we parse the bitmask by first expanding it into
242             # a string of bits
243 96         273 for (unpack "b*", $vec[$_]) {
244             # and then repeatedly matching a regex against it
245 96         436 while (/1/g) {
246             # and use the resulting string position as fd
247             $_ && $_->[2]()
248 50 50 33     89 for @{ $fds->[W][(pos) - 1] || [] };
  50         514  
249             }
250             }
251             }
252             } elsif (AnyEvent::WIN32 && $fds && $! == AnyEvent::Util::WSAEINVAL) {
253             # buggy microshit windoze asks us to route around it
254             CORE::select undef, undef, undef, $wait if $wait;
255             } elsif (!@timer || $timer[0][0] > $MNOW && !$fds) {
256 4   0     69 $$$_ && $$$_->() for @idle = grep $$$_, @idle;
257             }
258             }
259             }
260              
261             sub run {
262 0     0 1 0 one_event while 1;
263             }
264              
265             sub io($$$) {
266 26     26 0 88 my ($fd, $write, $cb) = @_;
267              
268 26 100       111 defined ($fd = fileno $fd)
269             or $fd = $_[0];
270              
271 26         127 my $self = bless [
272             $fd,
273             $write,
274             $cb,
275             # q-idx
276             ], "AnyEvent::Loop::io";
277              
278 26         654 my $fds = $fds[$self->[1]];
279              
280             # add watcher to fds structure
281 26   100     131 my $q = $fds->[W][$fd] ||= [];
282              
283 26         108 (vec $fds->[V], $fd, 1) = 1;
284              
285 26         67 $self->[3] = @$q;
286 26         46 push @$q, $self;
287 26         134 weaken $q->[-1];
288              
289 26         238 $self
290             }
291              
292             sub AnyEvent::Loop::io::DESTROY {
293 21     21   404 my ($self) = @_;
294              
295 21         40 my $fds = $fds[$self->[1]];
296              
297             # remove watcher from fds structure
298 21         36 my $fd = $self->[0];
299              
300 21 100       28 if (@{ $fds->[W][$fd] } == 1) {
  21         54  
301 16         25 delete $fds->[W][$fd];
302 16         368 (vec $fds->[V], $fd, 1) = 0;
303             } else {
304 5         16 my $q = $fds->[W][$fd];
305 5         13 my $last = pop @$q;
306              
307 5 100       30 if ($last != $self) {
308 3         11 weaken ($q->[$self->[3]] = $last);
309 3         32 $last->[3] = $self->[3];
310             }
311             }
312             }
313              
314             sub timer($$$) {
315 33     33 1 265 my ($after, $interval, $cb) = @_;
316            
317 33         64 my $self;
318              
319 33 100       94 if ($interval) {
320             $self = [$MNOW + $after , sub {
321 0     0   0 $_[0][0] = List::Util::max $_[0][0] + $interval, $MNOW;
322 0         0 push @timer, $_[0];
323 0         0 weaken $timer[-1];
324 0 0       0 $need_sort = $_[0][0] if $_[0][0] < $need_sort;
325 0         0 &$cb;
326 1         6 }];
327             } else {
328 32         122 $self = [$MNOW + $after, $cb];
329             }
330              
331 33         81 push @timer, $self;
332 33         432 weaken $timer[-1];
333 33 100       157 $need_sort = $self->[0] if $self->[0] < $need_sort;
334              
335 33         138 $self
336             }
337              
338             sub idle($) {
339 0     0 0   my $cb = shift;
340              
341 0           push @idle, \\$cb;
342 0           weaken ${$idle[-1]};
  0            
343              
344 0           ${$idle[-1]}
  0            
345             }
346              
347             =head1 SEE ALSO
348              
349             L<AnyEvent>.
350              
351             =head1 AUTHOR
352              
353             Marc Lehmann <schmorp@schmorp.de>
354             http://anyevent.schmorp.de
355              
356             =cut
357              
358             1
359