--- AnyEvent/lib/AnyEvent.pm 2010/11/23 04:45:59 1.338 +++ AnyEvent/lib/AnyEvent.pm 2011/08/13 02:35:32 1.358 @@ -87,12 +87,12 @@ AnyEvent is different: AnyEvent + POE works fine. AnyEvent + Glib works fine. AnyEvent + Tk works fine etc. etc. but none of these work together -with the rest: POE + IO::Async? No go. Tk + Event? No go. Again: if -your module uses one of those, every user of your module has to use it, -too. But if your module uses AnyEvent, it works transparently with all -event models it supports (including stuff like IO::Async, as long as those -use one of the supported event loops. It is easy to add new event loops -to AnyEvent, too, so it is future-proof). +with the rest: POE + EV? No go. Tk + Event? No go. Again: if your module +uses one of those, every user of your module has to use it, too. But if +your module uses AnyEvent, it works transparently with all event models it +supports (including stuff like IO::Async, as long as those use one of the +supported event loops. It is easy to add new event loops to AnyEvent, too, +so it is future-proof). In addition to being free of having to use I, AnyEvent also is free of bloat and policy: with POE or similar @@ -123,11 +123,11 @@ During the first call of any watcher-creation method, the module tries to detect the currently loaded event loop by probing whether one of the -following modules is already loaded: L, L, +following modules is already loaded: L, L, L, L, L, L, L, L. The first one found is used. If none are detected, the module tries to load the first four modules in the order given; but note that if L is not -available, the pure-perl L should always work, so +available, the pure-perl L should always work, so the other two are not normally tried. Because AnyEvent first checks for modules that are already loaded, loading @@ -144,9 +144,9 @@ as very few modules hardcode event loops without announcing this very loudly. -The pure-perl implementation of AnyEvent is called -C. Like other event modules you can load it -explicitly and enjoy the high availability of that event loop :) +The pure-perl implementation of AnyEvent is called C. Like +other event modules you can load it explicitly and enjoy the high +availability of that event loop :) =head1 WATCHERS @@ -358,9 +358,9 @@ =item AnyEvent->now_update -Some event loops (such as L or L) cache -the current time for each loop iteration (see the discussion of L<< -AnyEvent->now >>, above). +Some event loops (such as L or L) cache the current +time for each loop iteration (see the discussion of L<< AnyEvent->now >>, +above). When a callback runs for a long time (or when the process sleeps), then this "current" time will differ substantially from the real time, which @@ -484,8 +484,8 @@ C). As most event loops do not support waiting for child events, they will be -emulated by AnyEvent in most cases, in which the latency and race problems -mentioned in the description of signal watchers apply. +emulated by AnyEvent in most cases, in which case the latency and race +problems mentioned in the description of signal watchers apply. Example: fork a process and wait for it @@ -862,7 +862,7 @@ AnyEvent itself. AnyEvent::Impl::EV based on EV (interface to libev, best choice). - AnyEvent::Impl::Perl pure-perl implementation, fast and portable. + AnyEvent::Impl::Perl pure-perl AnyEvent::Loop, fast and portable. =item Backends that are transparently being picked up when they are used. @@ -878,6 +878,9 @@ AnyEvent::Impl::EventLib based on Event::Lib, leaks memory and worse. AnyEvent::Impl::POE based on POE, very slow, some limitations. AnyEvent::Impl::Irssi used when running within irssi. + AnyEvent::Impl::IOAsync based on IO::Async. + AnyEvent::Impl::Cocoa based on Cocoa::EventLoop. + AnyEvent::Impl::FLTK2 based on FLTK (fltk 2 binding). =item Backends with special needs. @@ -888,14 +891,6 @@ AnyEvent::Impl::Qt based on Qt. -Support for IO::Async can only be partial, as it is too broken and -architecturally limited to even support the AnyEvent API. It also -is the only event loop that needs the loop to be set explicitly, so -it can only be used by a main program knowing about AnyEvent. See -L for the gory details. - - AnyEvent::Impl::IOAsync based on IO::Async, cannot be autoprobed. - =item Event loops that are indirectly supported via other backends. Some event loops can be supported via other modules: @@ -1012,6 +1007,46 @@ push @AnyEvent::post_detect, sub { require Coro::AnyEvent }; } +=item AnyEvent::postpone { BLOCK } + +Arranges for the block to be executed as soon as possible, but not before +the call itself returns. In practise, the block will be executed just +before the event loop polls for new events, or shortly afterwards. + +This function never returns anything (to make the C idiom more useful. + +To understand the usefulness of this function, consider a function that +asynchronously does something for you and returns some transaction +object or guard to let you cancel the operation. For example, +C: + + # start a conenction attempt unless one is active + $self->{connect_guard} ||= AnyEvent::Socket::tcp_connect "www.example.net", 80, sub { + delete $self->{connect_guard}; + ... + }; + +Imagine that this function could instantly call the callback, for +example, because it detects an obvious error such as a negative port +number. Invoking the callback before the function returns causes problems +however: the callback will be called and will try to delete the guard +object. But since the function hasn't returned yet, there is nothing to +delete. When the function eventually returns it will assign the guard +object to C<< $self->{connect_guard} >>, where it will likely never be +deleted, so the program thinks it is still trying to connect. + +This is where C should be used. Instead of calling the +callback directly on error: + + $cb->(undef), return # signal error to callback, BAD! + if $some_error_condition; + +It should use C: + + AnyEvent::postpone { $cb->(undef) }, return # signal error to callback, later + if $some_error_condition; + =back =head1 WHAT TO DO IN A MODULE @@ -1054,7 +1089,7 @@ might choose the wrong one unless you load the correct one yourself. You can chose to use a pure-perl implementation by loading the -C module, which gives you similar behaviour +C module, which gives you similar behaviour everywhere, but letting AnyEvent chose the model is generally better. =head2 MAINLOOP EMULATION @@ -1159,8 +1194,8 @@ # basically a tuned-down version of common::sense sub common_sense { - # from common:.sense 3.3 - ${^WARNING_BITS} ^= ${^WARNING_BITS} ^ "\x3c\x3f\x33\x00\x0f\xf3\x0f\xc0\xf0\xfc\x33\x00"; + # from common:.sense 3.4 + ${^WARNING_BITS} ^= ${^WARNING_BITS} ^ "\x3c\x3f\x33\x00\x0f\xf0\x0f\xc0\xf0\xfc\x33\x00"; # use strict vars subs - NO UTF-8, as Util.pm doesn't like this atm. (uts46data.pl) $^H |= 0x00000600; } @@ -1169,10 +1204,9 @@ use Carp (); -our $VERSION = '5.29'; +our $VERSION = '5.34'; our $MODEL; -our $AUTOLOAD; our @ISA; our @REGISTRY; @@ -1202,34 +1236,6 @@ $ENV{PERL_ANYEVENT_PROTOCOLS} || "ipv4,ipv6"; } -my @models = ( - [EV:: => AnyEvent::Impl::EV:: , 1], - [AnyEvent::Impl::Perl:: => AnyEvent::Impl::Perl:: , 1], - # everything below here will not (normally) be autoprobed - # as the pureperl backend should work everywhere - # and is usually faster - [Event:: => AnyEvent::Impl::Event::, 1], - [Glib:: => AnyEvent::Impl::Glib:: , 1], # becomes extremely slow with many watchers - [Event::Lib:: => AnyEvent::Impl::EventLib::], # too buggy - [Irssi:: => AnyEvent::Impl::Irssi::], # Irssi has a bogus "Event" package - [Tk:: => AnyEvent::Impl::Tk::], # crashes with many handles - [Qt:: => AnyEvent::Impl::Qt::], # requires special main program - [POE::Kernel:: => AnyEvent::Impl::POE::], # lasciate ogni speranza - [Wx:: => AnyEvent::Impl::POE::], - [Prima:: => AnyEvent::Impl::POE::], - # IO::Async is just too broken - we would need workarounds for its - # byzantine signal and broken child handling, among others. - # IO::Async is rather hard to detect, as it doesn't have any - # obvious default class. - [IO::Async:: => AnyEvent::Impl::IOAsync::], # requires special main program - [IO::Async::Loop:: => AnyEvent::Impl::IOAsync::], # requires special main program - [IO::Async::Notifier:: => AnyEvent::Impl::IOAsync::], # requires special main program - [AnyEvent::Impl::IOAsync:: => AnyEvent::Impl::IOAsync::], # requires special main program -); - -our %method = map +($_ => 1), - qw(io timer time now now_update signal child idle condvar one_event DESTROY); - our @post_detect; sub post_detect(&) { @@ -1246,15 +1252,65 @@ @post_detect = grep $_ != ${$_[0]}, @post_detect; } -sub detect() { - # free some memory - *detect = sub () { $MODEL }; +our $POSTPONE_W; +our @POSTPONE; + +sub _postpone_exec { + undef $POSTPONE_W; + + &{ shift @POSTPONE } + while @POSTPONE; +} + +sub postpone(&) { + push @POSTPONE, shift; + + $POSTPONE_W ||= AE::timer (0, 0, \&_postpone_exec); + + () +} + +our @models = ( + [EV:: => AnyEvent::Impl::EV:: , 1], + [AnyEvent::Loop:: => AnyEvent::Impl::Perl:: , 1], + # everything below here will not (normally) be autoprobed + # as the pure perl backend should work everywhere + # and is usually faster + [Event:: => AnyEvent::Impl::Event::, 1], + [Glib:: => AnyEvent::Impl::Glib:: , 1], # becomes extremely slow with many watchers + [Event::Lib:: => AnyEvent::Impl::EventLib::], # too buggy + [Irssi:: => AnyEvent::Impl::Irssi::], # Irssi has a bogus "Event" package + [Tk:: => AnyEvent::Impl::Tk::], # crashes with many handles + [Qt:: => AnyEvent::Impl::Qt::], # requires special main program + [POE::Kernel:: => AnyEvent::Impl::POE::], # lasciate ogni speranza + [Wx:: => AnyEvent::Impl::POE::], + [Prima:: => AnyEvent::Impl::POE::], + [IO::Async::Loop:: => AnyEvent::Impl::IOAsync::], # a bitch to autodetect + [Cocoa::EventLoop:: => AnyEvent::Impl::Cocoa::], + [FLTK:: => AnyEvent::Impl::FLTK2::], +); + +# all autoloaded methods reserve the complete glob, not just the method slot. +# due to bugs in perls method cache implementation. +our @methods = qw(io timer time now now_update signal child idle condvar); +sub detect() { local $!; # for good measure - local $SIG{__DIE__}; + local $SIG{__DIE__}; # we use eval - if ($ENV{PERL_ANYEVENT_MODEL} =~ /^([a-zA-Z]+)$/) { - my $model = "AnyEvent::Impl::$1"; + # free some memory + *detect = sub () { $MODEL }; + # undef &func doesn't correctly update the method cache. grmbl. + # so we delete the whole glob. grmbl. + # otoh, perl doesn't let me undef an active usb, but it lets me free + # a glob with an active sub. hrm. i hope it works, but perl is + # usually buggy in this department. sigh. + delete @{"AnyEvent::"}{@methods}; + undef @methods; + + if ($ENV{PERL_ANYEVENT_MODEL} =~ /^([a-zA-Z0-9:]+)$/) { + my $model = $1; + $model = "AnyEvent::Impl::$model" unless $model =~ s/::$//; if (eval "require $model") { $MODEL = $model; warn "AnyEvent: loaded model '$model' (forced by \$ENV{PERL_ANYEVENT_MODEL}), using it.\n" if $VERBOSE >= 2; @@ -1297,21 +1353,39 @@ } } - @models = (); # free probe data + # free memory only needed for probing + undef @models; + undef @REGISTRY; push @{"$MODEL\::ISA"}, "AnyEvent::Base"; unshift @ISA, $MODEL; # now nuke some methods that are overridden by the backend. - # SUPER is not allowed. + # SUPER usage is not allowed in these. for (qw(time signal child idle)) { undef &{"AnyEvent::Base::$_"} if defined &{"$MODEL\::$_"}; } - require AnyEvent::Strict if $ENV{PERL_ANYEVENT_STRICT}; + if ($ENV{PERL_ANYEVENT_STRICT}) { + require AnyEvent::Strict; + } + + if ($ENV{PERL_ANYEVENT_DEBUG_WRAP}) { + require AnyEvent::Debug; + AnyEvent::Debug::wrap ($ENV{PERL_ANYEVENT_DEBUG_WRAP}); + } + + if (exists $ENV{PERL_ANYEVENT_DEBUG_SHELL}) { + require AnyEvent::Socket; + require AnyEvent::Debug; + + my ($host, $service) = AnyEvent::Socket::parse_hostport ($ENV{PERL_ANYEVENT_DEBUG_SHELL}); + $AnyEvent::Debug::SHELL = AnyEvent::Debug::shell ($host, $service); + } (shift @post_detect)->() while @post_detect; + undef @post_detect; *post_detect = sub(&) { shift->(); @@ -1322,16 +1396,14 @@ $MODEL } -sub AUTOLOAD { - (my $func = $AUTOLOAD) =~ s/.*://; - - $method{$func} - or Carp::croak "$func: not a valid AnyEvent class method"; - - detect; - - my $class = shift; - $class->$func (@_); +for my $name (@methods) { + *$name = sub { + detect; + # we use goto because + # a) it makes the thunk more transparent + # b) it allows us to delete the thunk later + goto &{ UNIVERSAL::can AnyEvent => "SUPER::$name" } + }; } # utility function to dup a filehandle. this is used by many backends @@ -1365,45 +1437,54 @@ our $VERSION = $AnyEvent::VERSION; -# fall back to the main API by default - backends and AnyEvent::Base -# implementations can overwrite these. +sub _reset() { + eval q{ + # fall back to the main API by default - backends and AnyEvent::Base + # implementations can overwrite these. -sub io($$$) { - AnyEvent->io (fh => $_[0], poll => $_[1] ? "w" : "r", cb => $_[2]) -} + sub io($$$) { + AnyEvent->io (fh => $_[0], poll => $_[1] ? "w" : "r", cb => $_[2]) + } -sub timer($$$) { - AnyEvent->timer (after => $_[0], interval => $_[1], cb => $_[2]) -} + sub timer($$$) { + AnyEvent->timer (after => $_[0], interval => $_[1], cb => $_[2]) + } -sub signal($$) { - AnyEvent->signal (signal => $_[0], cb => $_[1]) -} + sub signal($$) { + AnyEvent->signal (signal => $_[0], cb => $_[1]) + } -sub child($$) { - AnyEvent->child (pid => $_[0], cb => $_[1]) -} + sub child($$) { + AnyEvent->child (pid => $_[0], cb => $_[1]) + } -sub idle($) { - AnyEvent->idle (cb => $_[0]) -} + sub idle($) { + AnyEvent->idle (cb => $_[0]); + } -sub cv(;&) { - AnyEvent->condvar (@_ ? (cb => $_[0]) : ()) -} + sub cv(;&) { + AnyEvent->condvar (@_ ? (cb => $_[0]) : ()) + } -sub now() { - AnyEvent->now -} + sub now() { + AnyEvent->now + } -sub now_update() { - AnyEvent->now_update -} + sub now_update() { + AnyEvent->now_update + } -sub time() { - AnyEvent->time + sub time() { + AnyEvent->time + } + + *postpone = \&AnyEvent::postpone; + }; + die if $@; } +BEGIN { _reset } + package AnyEvent::Base; # default implementations for many methods @@ -1431,7 +1512,12 @@ sub now_update { } +sub _poll { + Carp::croak "$AnyEvent::MODEL does not support blocking waits. Caught"; +} + # default implementation for ->condvar +# in fact, the default should not be overwritten sub condvar { eval q{ # poor man's autoloading {} @@ -1611,7 +1697,7 @@ while (%SIG_EV) { for (keys %SIG_EV) { delete $SIG_EV{$_}; - $_->() for values %{ $SIG_CB{$_} || {} }; + &$_ for values %{ $SIG_CB{$_} || {} }; } } }; @@ -1626,7 +1712,6 @@ our %PID_CB; our $CHLD_W; our $CHLD_DELAY_W; -our $WNOHANG; # used by many Impl's sub _emit_childstatus($$) { @@ -1643,21 +1728,16 @@ my $pid; AnyEvent->_emit_childstatus ($pid, $?) - while ($pid = waitpid -1, $WNOHANG) > 0; + while ($pid = waitpid -1, WNOHANG) > 0; }; *child = sub { my (undef, %arg) = @_; - defined (my $pid = $arg{pid} + 0) - or Carp::croak "required option 'pid' is missing"; + my $pid = $arg{pid}; + my $cb = $arg{cb}; - $PID_CB{$pid}{$arg{cb}} = $arg{cb}; - - # WNOHANG is almost cetrainly 1 everywhere - $WNOHANG ||= $^O =~ /^(?:openbsd|netbsd|linux|freebsd|cygwin|MSWin32)$/ - ? 1 - : eval { local $SIG{__DIE__}; require POSIX; &POSIX::WNOHANG } || 1; + $PID_CB{$pid}{$cb+0} = $cb; unless ($CHLD_W) { $CHLD_W = AE::signal CHLD => \&_sigchld; @@ -1665,13 +1745,13 @@ &_sigchld; } - bless [$pid, $arg{cb}], "AnyEvent::Base::child" + bless [$pid, $cb+0], "AnyEvent::Base::child" }; *AnyEvent::Base::child::DESTROY = sub { - my ($pid, $cb) = @{$_[0]}; + my ($pid, $icb) = @{$_[0]}; - delete $PID_CB{$pid}{$cb}; + delete $PID_CB{$pid}{$icb}; delete $PID_CB{$pid} unless keys %{ $PID_CB{$pid} }; undef $CHLD_W unless keys %PID_CB; @@ -1694,9 +1774,9 @@ $rcb = sub { if ($cb) { - $w = _time; + $w = AE::time; &$cb; - $w = _time - $w; + $w = AE::time - $w; # never use more then 50% of the time for the idle watcher, # within some limits @@ -1753,6 +1833,10 @@ # nop } +sub _wait { + AnyEvent->_poll until $_[0]{_ae_sent}; +} + sub send { my $cv = shift; $cv->{_ae_sent} = [@_]; @@ -1769,20 +1853,21 @@ $_[0]{_ae_sent} } -sub _wait { - $WAITING - and !$_[0]{_ae_sent} - and Carp::croak "AnyEvent::CondVar: recursive blocking wait detected"; +sub recv { + unless ($_[0]{_ae_sent}) { + $WAITING + and Carp::croak "AnyEvent::CondVar: recursive blocking wait attempted"; - local $WAITING = 1; - AnyEvent->one_event while !$_[0]{_ae_sent}; -} + local $WAITING = 1; + $_[0]->_wait; + } -sub recv { - $_[0]->_wait; + $_[0]{_ae_croak} + and Carp::croak $_[0]{_ae_croak}; - Carp::croak $_[0]{_ae_croak} if $_[0]{_ae_croak}; - wantarray ? @{ $_[0]{_ae_sent} } : $_[0]{_ae_sent}[0] + wantarray + ? @{ $_[0]{_ae_sent} } + : $_[0]{_ae_sent}[0] } sub cb { @@ -1808,7 +1893,7 @@ # undocumented/compatibility with pre-3.4 *broadcast = \&send; -*wait = \&_wait; +*wait = \&recv; =head1 ERROR AND EXCEPTION HANDLING @@ -1870,18 +1955,39 @@ C in your environment while developing programs can be very useful, however. +=item C + +If this env variable is set, then its contents will be +interpreted by C and an +C is bound on that port. The shell object is saved +in C<$AnyEvent::Debug::SHELL>. + +For example, to bind a debug shell on a unix domain socket in +F, you could use this: + + PERL_ANYEVENT_DEBUG_SHELL=unix/:/tmp/debug.sock perlprog + +=item C + +Can be set to C<0>, C<1> or C<2> and enables wrapping of all watchers for +debugging purposes. See C for details. + =item C This can be used to specify the event model to be used by AnyEvent, before -auto detection and -probing kicks in. It must be a string consisting -entirely of ASCII letters. The string C gets prepended -and the resulting module name is loaded and if the load was successful, -used as event model. If it fails to load AnyEvent will proceed with +auto detection and -probing kicks in. + +It normally is a string consisting entirely of ASCII letters (e.g. C +or C). The string C gets prepended and the +resulting module name is loaded and - if the load was successful - used as +event model backend. If it fails to load then AnyEvent will proceed with auto detection and -probing. -This functionality might change in future versions. +If the string ends with C<::> instead (e.g. C) then +nothing gets prepended and the module name is used as-is (hint: C<::> at +the end of a string designates a module name and quotes it appropriately). -For example, to force the pure perl model (L) you +For example, to force the pure perl model (L) you could start your program like this: PERL_ANYEVENT_MODEL=Perl perl ... @@ -2590,7 +2696,7 @@ This module is part of perl since release 5.008. It will be used when the chosen event library does not come with a timing source of its own. The -pure-perl event loop (L) will additionally use it to +pure-perl event loop (L) will additionally load it to try to use a monotonic clock for timing stability. =back @@ -2668,8 +2774,8 @@ Utility functions: L. -Event modules: L, L, L, L, L, -L, L, L, L, L. +Event modules: L, L, L, L, +L, L, L, L, L, L, L. Implementations: L, L, L, L, L,