blib/lib/AnyEvent/Impl/Perl.pm untested

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