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 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 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
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
71             case" where most of the fds are active (which suits C
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
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, 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 13     13   974 use Scalar::Util qw(weaken);
  13         26  
  13         1600  
121 13     13   87 use List::Util ();
  13         24  
  13         199  
122              
123 13     13   59 use AnyEvent (); BEGIN { AnyEvent::common_sense }
  13     13   23  
  13         242  
  13         64  
124 13     13   9808 use AnyEvent::Util ();
  13         35  
  13         4820  
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 13     13   95 local $SIG{__DIE__}; # protect us against the many broken __DIE__ handlers out there
134 13     13   939 my $time_hires = eval "use Time::HiRes (); 1";
  13         6902  
  13         18036  
  13         142  
135 13     13   712 my $clk_tck = eval "use POSIX (); POSIX::sysconf (POSIX::_SC_CLK_TCK ())";
  13         5946  
  13         74588  
  13         353  
136 13         36 my $round; # actual granularity
137              
138 13 50 33     690 if ($time_hires && eval "&Time::HiRes::clock_gettime (Time::HiRes::CLOCK_MONOTONIC ())") {
    0 0        
    0 0        
139 13         626 AE::log 8 => "Using CLOCK_MONOTONIC as timebase.";
140             *_update_clock = sub {
141 173     173   531 $NOW = &Time::HiRes::time;
142 173         458 $MNOW = Time::HiRes::clock_gettime (&Time::HiRes::CLOCK_MONOTONIC);
143 13         65 };
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 13 50       94 $round = 0.001 if $round < 0.001; # 1ms is enough for us
174 13         44 $round -= $round * 1e-2; # 0.1 => 0.099
175 13         14434 eval "sub ROUNDUP() { $round }";
176             }
177              
178             _update_clock;
179              
180             # rely on AnyEvent:Base::time to provide time
181 37     37 0 112 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 92     92 1 383 _update_clock;
201              
202             # first sort timers if required (slow)
203 92 100       534 if ($MNOW >= $need_sort) {
204 15         31 $need_sort = 1e300;
205 15         72 @timer = sort { $a->[0] <=> $b->[0] } @timer;
  6         26  
206             }
207              
208             # handle all pending timers
209 92 100 100     492 if (@timer && $timer[0][0] <= $MNOW) {
210 24   100     62 do {
211 25         118 my $timer = shift @timer;
212 25 100       239 $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 68 100 100     448 my ($wait, @vec, $fds)
220             = (@timer && $timer[0][0] < $need_sort ? $timer[0][0] : $need_sort) - $MNOW;
221              
222 68 100       193 $wait = $wait < MAXWAIT ? $wait + ROUNDUP : MAXWAIT;
223 68 50       138 $wait = 0 if @idle;
224              
225 68         552789 $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 68         834 _update_clock;
232              
233 68 100 66     752 if ($fds > 0) {
    100 66        
234             # buggy microshit windows errornously sets exceptfds instead of writefds
235 48         76 $vec[1] |= $vec[2] if AnyEvent::WIN32;
236              
237             # prefer write watchers, because they might reduce memory pressure.
238 48         101 for (1, 0) {
239 96         258 my $fds = $fds[$_];
240              
241             # we parse the bitmask by first expanding it into
242             # a string of bits
243 96         283 for (unpack "b*", $vec[$_]) {
244             # and then repeatedly matching a regex against it
245 96         557 while (/1/g) {
246             # and use the resulting string position as fd
247             $_ && $_->[2]()
248 50 50 33     91 for @{ $fds->[W][(pos) - 1] || [] };
  50         556  
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     47 $$$_ && $$$_->() 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 89 my ($fd, $write, $cb) = @_;
267              
268 26 100       115 defined ($fd = fileno $fd)
269             or $fd = $_[0];
270              
271 26         129 my $self = bless [
272             $fd,
273             $write,
274             $cb,
275             # q-idx
276             ], "AnyEvent::Loop::io";
277              
278 26         120 my $fds = $fds[$self->[1]];
279              
280             # add watcher to fds structure
281 26   100     132 my $q = $fds->[W][$fd] ||= [];
282              
283 26         126 (vec $fds->[V], $fd, 1) = 1;
284              
285 26         81 $self->[3] = @$q;
286 26         52 push @$q, $self;
287 26         86 weaken $q->[-1];
288              
289 26         282 $self
290             }
291              
292             sub AnyEvent::Loop::io::DESTROY {
293 21     21   223 my ($self) = @_;
294              
295 21         46 my $fds = $fds[$self->[1]];
296              
297             # remove watcher from fds structure
298 21         33 my $fd = $self->[0];
299              
300 21 100       30 if (@{ $fds->[W][$fd] } == 1) {
  21         113  
301 16         31 delete $fds->[W][$fd];
302 16         430 (vec $fds->[V], $fd, 1) = 0;
303             } else {
304 5         11 my $q = $fds->[W][$fd];
305 5         12 my $last = pop @$q;
306              
307 5 100       45 if ($last != $self) {
308 3         14 weaken ($q->[$self->[3]] = $last);
309 3         30 $last->[3] = $self->[3];
310             }
311             }
312             }
313              
314             sub timer($$$) {
315 30     30 1 223 my ($after, $interval, $cb) = @_;
316            
317 30         53 my $self;
318              
319 30 100       77 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 29         107 $self = [$MNOW + $after, $cb];
329             }
330              
331 30         90 push @timer, $self;
332 30         140 weaken $timer[-1];
333 30 100       110 $need_sort = $self->[0] if $self->[0] < $need_sort;
334              
335 30         174 $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.
350              
351             =head1 AUTHOR
352              
353             Marc Lehmann
354             http://anyevent.schmorp.de
355              
356             =cut
357              
358             1
359