ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent/lib/AnyEvent.pm
(Generate patch)

Comparing AnyEvent/lib/AnyEvent.pm (file contents):
Revision 1.406 by root, Thu Nov 15 01:17:29 2012 UTC vs.
Revision 1.418 by root, Tue Jan 21 16:48:34 2014 UTC

271 271
272Example 2: fire an event after 0.5 seconds, then roughly every second. 272Example 2: fire an event after 0.5 seconds, then roughly every second.
273 273
274 my $w = AnyEvent->timer (after => 0.5, interval => 1, cb => sub { 274 my $w = AnyEvent->timer (after => 0.5, interval => 1, cb => sub {
275 warn "timeout\n"; 275 warn "timeout\n";
276 }; 276 });
277 277
278=head3 TIMING ISSUES 278=head3 TIMING ISSUES
279 279
280There are two ways to handle timers: based on real time (relative, "fire 280There are two ways to handle timers: based on real time (relative, "fire
281in 10 seconds") and based on wallclock time (absolute, "fire at 12 281in 10 seconds") and based on wallclock time (absolute, "fire at 12
487 487
488Example: fork a process and wait for it 488Example: fork a process and wait for it
489 489
490 my $done = AnyEvent->condvar; 490 my $done = AnyEvent->condvar;
491 491
492 # this forks and immediately calls exit in the child. this
493 # normally has all sorts of bad consequences for your parent,
494 # so take this as an example only. always fork and exec,
495 # or call POSIX::_exit, in real code.
492 my $pid = fork or exit 5; 496 my $pid = fork or exit 5;
493 497
494 my $w = AnyEvent->child ( 498 my $w = AnyEvent->child (
495 pid => $pid, 499 pid => $pid,
496 cb => sub { 500 cb => sub {
745This works because for every event source (EOF on file handle), there is 749This works because for every event source (EOF on file handle), there is
746one call to C<begin>, so the condvar waits for all calls to C<end> before 750one call to C<begin>, so the condvar waits for all calls to C<end> before
747sending. 751sending.
748 752
749The ping example mentioned above is slightly more complicated, as the 753The ping example mentioned above is slightly more complicated, as the
750there are results to be passwd back, and the number of tasks that are 754there are results to be passed back, and the number of tasks that are
751begun can potentially be zero: 755begun can potentially be zero:
752 756
753 my $cv = AnyEvent->condvar; 757 my $cv = AnyEvent->condvar;
754 758
755 my %result; 759 my %result;
763 }; 767 };
764 } 768 }
765 769
766 $cv->end; 770 $cv->end;
767 771
772 ...
773
774 my $results = $cv->recv;
775
768This code fragment supposedly pings a number of hosts and calls 776This code fragment supposedly pings a number of hosts and calls
769C<send> after results for all then have have been gathered - in any 777C<send> after results for all then have have been gathered - in any
770order. To achieve this, the code issues a call to C<begin> when it starts 778order. To achieve this, the code issues a call to C<begin> when it starts
771each ping request and calls C<end> when it has received some result for 779each ping request and calls C<end> when it has received some result for
772it. Since C<begin> and C<end> only maintain a counter, the order in which 780it. Since C<begin> and C<end> only maintain a counter, the order in which
807 815
808In list context, all parameters passed to C<send> will be returned, 816In list context, all parameters passed to C<send> will be returned,
809in scalar context only the first one will be returned. 817in scalar context only the first one will be returned.
810 818
811Note that doing a blocking wait in a callback is not supported by any 819Note that doing a blocking wait in a callback is not supported by any
812event loop, that is, recursive invocation of a blocking C<< ->recv 820event loop, that is, recursive invocation of a blocking C<< ->recv >> is
813>> is not allowed, and the C<recv> call will C<croak> if such a 821not allowed and the C<recv> call will C<croak> if such a condition is
814condition is detected. This condition can be slightly loosened by using 822detected. This requirement can be dropped by relying on L<Coro::AnyEvent>
815L<Coro::AnyEvent>, which allows you to do a blocking C<< ->recv >> from 823, which allows you to do a blocking C<< ->recv >> from any thread
816any thread that doesn't run the event loop itself. 824that doesn't run the event loop itself. L<Coro::AnyEvent> is loaded
825automatically when L<Coro> is used with L<AnyEvent>, so code does not need
826to do anything special to take advantage of that: any code that would
827normally block your program because it calls C<recv>, be executed in an
828C<async> thread instead without blocking other threads.
817 829
818Not all event models support a blocking wait - some die in that case 830Not all event models support a blocking wait - some die in that case
819(programs might want to do that to stay interactive), so I<if you are 831(programs might want to do that to stay interactive), so I<if you are
820using this from a module, never require a blocking wait>. Instead, let the 832using this from a module, never require a blocking wait>. Instead, let the
821caller decide whether the call will block or not (for example, by coupling 833caller decide whether the call will block or not (for example, by coupling
1021To understand the usefulness of this function, consider a function that 1033To understand the usefulness of this function, consider a function that
1022asynchronously does something for you and returns some transaction 1034asynchronously does something for you and returns some transaction
1023object or guard to let you cancel the operation. For example, 1035object or guard to let you cancel the operation. For example,
1024C<AnyEvent::Socket::tcp_connect>: 1036C<AnyEvent::Socket::tcp_connect>:
1025 1037
1026 # start a conenction attempt unless one is active 1038 # start a connection attempt unless one is active
1027 $self->{connect_guard} ||= AnyEvent::Socket::tcp_connect "www.example.net", 80, sub { 1039 $self->{connect_guard} ||= AnyEvent::Socket::tcp_connect "www.example.net", 80, sub {
1028 delete $self->{connect_guard}; 1040 delete $self->{connect_guard};
1029 ... 1041 ...
1030 }; 1042 };
1031 1043
1139a longer non-exhaustive list), and the list is heavily biased towards 1151a longer non-exhaustive list), and the list is heavily biased towards
1140modules of the AnyEvent author himself :) 1152modules of the AnyEvent author himself :)
1141 1153
1142=over 4 1154=over 4
1143 1155
1144=item L<AnyEvent::Util> 1156=item L<AnyEvent::Util> (part of the AnyEvent distribution)
1145 1157
1146Contains various utility functions that replace often-used blocking 1158Contains various utility functions that replace often-used blocking
1147functions such as C<inet_aton> with event/callback-based versions. 1159functions such as C<inet_aton> with event/callback-based versions.
1148 1160
1149=item L<AnyEvent::Socket> 1161=item L<AnyEvent::Socket> (part of the AnyEvent distribution)
1150 1162
1151Provides various utility functions for (internet protocol) sockets, 1163Provides various utility functions for (internet protocol) sockets,
1152addresses and name resolution. Also functions to create non-blocking tcp 1164addresses and name resolution. Also functions to create non-blocking tcp
1153connections or tcp servers, with IPv6 and SRV record support and more. 1165connections or tcp servers, with IPv6 and SRV record support and more.
1154 1166
1155=item L<AnyEvent::Handle> 1167=item L<AnyEvent::Handle> (part of the AnyEvent distribution)
1156 1168
1157Provide read and write buffers, manages watchers for reads and writes, 1169Provide read and write buffers, manages watchers for reads and writes,
1158supports raw and formatted I/O, I/O queued and fully transparent and 1170supports raw and formatted I/O, I/O queued and fully transparent and
1159non-blocking SSL/TLS (via L<AnyEvent::TLS>). 1171non-blocking SSL/TLS (via L<AnyEvent::TLS>).
1160 1172
1161=item L<AnyEvent::DNS> 1173=item L<AnyEvent::DNS> (part of the AnyEvent distribution)
1162 1174
1163Provides rich asynchronous DNS resolver capabilities. 1175Provides rich asynchronous DNS resolver capabilities.
1164 1176
1165=item L<AnyEvent::HTTP>, L<AnyEvent::IRC>, L<AnyEvent::XMPP>, L<AnyEvent::GPSD>, L<AnyEvent::IGS>, L<AnyEvent::FCP> 1177=item L<AnyEvent::HTTP>, L<AnyEvent::IRC>, L<AnyEvent::XMPP>, L<AnyEvent::GPSD>, L<AnyEvent::IGS>, L<AnyEvent::FCP>
1166 1178
1167Implement event-based interfaces to the protocols of the same name (for 1179Implement event-based interfaces to the protocols of the same name (for
1168the curious, IGS is the International Go Server and FCP is the Freenet 1180the curious, IGS is the International Go Server and FCP is the Freenet
1169Client Protocol). 1181Client Protocol).
1170 1182
1171=item L<AnyEvent::AIO> 1183=item L<AnyEvent::AIO> (part of the AnyEvent distribution)
1172 1184
1173Truly asynchronous (as opposed to non-blocking) I/O, should be in the 1185Truly asynchronous (as opposed to non-blocking) I/O, should be in the
1174toolbox of every event programmer. AnyEvent::AIO transparently fuses 1186toolbox of every event programmer. AnyEvent::AIO transparently fuses
1175L<IO::AIO> and AnyEvent together, giving AnyEvent access to event-based 1187L<IO::AIO> and AnyEvent together, giving AnyEvent access to event-based
1176file I/O, and much more. 1188file I/O, and much more.
1189
1190=item L<AnyEvent::Fork>, L<AnyEvent::Fork::RPC>, L<AnyEvent::Fork::Pool>, L<AnyEvent::Fork::Remote>
1191
1192These let you safely fork new subprocesses, either locally or
1193remotely (e.g.v ia ssh), using some RPC protocol or not, without
1194the limitations normally imposed by fork (AnyEvent works fine for
1195example). Dynamically-resized worker pools are obviously included as well.
1196
1197And they are quite tiny and fast as well - "abusing" L<AnyEvent::Fork>
1198just to exec external programs can easily beat using C<fork> and C<exec>
1199(or even C<system>) in most programs.
1177 1200
1178=item L<AnyEvent::Filesys::Notify> 1201=item L<AnyEvent::Filesys::Notify>
1179 1202
1180AnyEvent is good for non-blocking stuff, but it can't detect file or 1203AnyEvent is good for non-blocking stuff, but it can't detect file or
1181path changes (e.g. "watch this directory for new files", "watch this 1204path changes (e.g. "watch this directory for new files", "watch this
1183do just that in a portbale fashion, supporting inotify on GNU/Linux and 1206do just that in a portbale fashion, supporting inotify on GNU/Linux and
1184some weird, without doubt broken, stuff on OS X to monitor files. It can 1207some weird, without doubt broken, stuff on OS X to monitor files. It can
1185fall back to blocking scans at regular intervals transparently on other 1208fall back to blocking scans at regular intervals transparently on other
1186platforms, so it's about as portable as it gets. 1209platforms, so it's about as portable as it gets.
1187 1210
1188(I haven't used it myself, but I haven't heard anybody complaining about 1211(I haven't used it myself, but it seems the biggest problem with it is
1189it yet). 1212it quite bad performance).
1190 1213
1191=item L<AnyEvent::DBI> 1214=item L<AnyEvent::DBI>
1192 1215
1193Executes L<DBI> requests asynchronously in a proxy process for you, 1216Executes L<DBI> requests asynchronously in a proxy process for you,
1194notifying you in an event-based way when the operation is finished. 1217notifying you in an event-based way when the operation is finished.
1195
1196=item L<AnyEvent::HTTPD>
1197
1198A simple embedded webserver.
1199 1218
1200=item L<AnyEvent::FastPing> 1219=item L<AnyEvent::FastPing>
1201 1220
1202The fastest ping in the west. 1221The fastest ping in the west.
1203 1222
1221 1240
1222=cut 1241=cut
1223 1242
1224package AnyEvent; 1243package AnyEvent;
1225 1244
1226# basically a tuned-down version of common::sense 1245BEGIN {
1227sub common_sense { 1246 require "AnyEvent/constants.pl";
1228 # from common:.sense 3.5 1247 &AnyEvent::common_sense;
1229 local $^W;
1230 ${^WARNING_BITS} ^= ${^WARNING_BITS} ^ "\x3c\x3f\x33\x00\x0f\xf0\x0f\xc0\xf0\xfc\x33\x00";
1231 # use strict vars subs - NO UTF-8, as Util.pm doesn't like this atm. (uts46data.pl)
1232 $^H |= 0x00000600;
1233} 1248}
1234
1235BEGIN { AnyEvent::common_sense }
1236 1249
1237use Carp (); 1250use Carp ();
1238 1251
1239our $VERSION = '7.03'; 1252our $VERSION = '7.07';
1240our $MODEL; 1253our $MODEL;
1241our @ISA; 1254our @ISA;
1242our @REGISTRY; 1255our @REGISTRY;
1243our $VERBOSE; 1256our $VERBOSE;
1244our %PROTOCOL; # (ipv4|ipv6) => (1|2), higher numbers are preferred 1257our %PROTOCOL; # (ipv4|ipv6) => (1|2), higher numbers are preferred
1245our $MAX_SIGNAL_LATENCY = $ENV{PERL_ANYEVENT_MAX_SIGNAL_LATENCY} || 10; # executes after the BEGIN block below (tainting!) 1258our $MAX_SIGNAL_LATENCY = $ENV{PERL_ANYEVENT_MAX_SIGNAL_LATENCY} || 10; # executes after the BEGIN block below (tainting!)
1246 1259
1247BEGIN { 1260BEGIN {
1248 require "AnyEvent/constants.pl";
1249
1250 eval "sub TAINT (){" . (${^TAINT}*1) . "}"; 1261 eval "sub TAINT (){" . (${^TAINT}*1) . "}";
1251 1262
1252 delete @ENV{grep /^PERL_ANYEVENT_/, keys %ENV} 1263 delete @ENV{grep /^PERL_ANYEVENT_/, keys %ENV}
1253 if ${^TAINT}; 1264 if ${^TAINT};
1254 1265
2199used, and preference will be given to protocols mentioned earlier in the 2210used, and preference will be given to protocols mentioned earlier in the
2200list. 2211list.
2201 2212
2202This variable can effectively be used for denial-of-service attacks 2213This variable can effectively be used for denial-of-service attacks
2203against local programs (e.g. when setuid), although the impact is likely 2214against local programs (e.g. when setuid), although the impact is likely
2204small, as the program has to handle conenction and other failures anyways. 2215small, as the program has to handle connection and other failures anyways.
2205 2216
2206Examples: C<PERL_ANYEVENT_PROTOCOLS=ipv4,ipv6> - prefer IPv4 over IPv6, 2217Examples: C<PERL_ANYEVENT_PROTOCOLS=ipv4,ipv6> - prefer IPv4 over IPv6,
2207but support both and try to use both. C<PERL_ANYEVENT_PROTOCOLS=ipv4> 2218but support both and try to use both. C<PERL_ANYEVENT_PROTOCOLS=ipv4>
2208- only support IPv4, never try to resolve or contact IPv6 2219- only support IPv4, never try to resolve or contact IPv6
2209addresses. C<PERL_ANYEVENT_PROTOCOLS=ipv6,ipv4> support either IPv4 or 2220addresses. C<PERL_ANYEVENT_PROTOCOLS=ipv6,ipv4> support either IPv4 or
2921This module is part of perl since release 5.008. It will be used when the 2932This module is part of perl since release 5.008. It will be used when the
2922chosen event library does not come with a timing source of its own. The 2933chosen event library does not come with a timing source of its own. The
2923pure-perl event loop (L<AnyEvent::Loop>) will additionally load it to 2934pure-perl event loop (L<AnyEvent::Loop>) will additionally load it to
2924try to use a monotonic clock for timing stability. 2935try to use a monotonic clock for timing stability.
2925 2936
2937=item L<AnyEvent::AIO> (and L<IO::AIO>)
2938
2939The default implementation of L<AnyEvent::IO> is to do I/O synchronously,
2940stopping programs while they access the disk, which is fine for a lot of
2941programs.
2942
2943Installing AnyEvent::AIO (and its IO::AIO dependency) makes it switch to
2944a true asynchronous implementation, so event processing can continue even
2945while waiting for disk I/O.
2946
2926=back 2947=back
2927 2948
2928 2949
2929=head1 FORK 2950=head1 FORK
2930 2951
2941usually happens when the first AnyEvent watcher is created, or the library 2962usually happens when the first AnyEvent watcher is created, or the library
2942is loaded). 2963is loaded).
2943 2964
2944If you have to fork, you must either do so I<before> creating your first 2965If you have to fork, you must either do so I<before> creating your first
2945watcher OR you must not use AnyEvent at all in the child OR you must do 2966watcher OR you must not use AnyEvent at all in the child OR you must do
2946something completely out of the scope of AnyEvent. 2967something completely out of the scope of AnyEvent (see below).
2947 2968
2948The problem of doing event processing in the parent I<and> the child 2969The problem of doing event processing in the parent I<and> the child
2949is much more complicated: even for backends that I<are> fork-aware or 2970is much more complicated: even for backends that I<are> fork-aware or
2950fork-safe, their behaviour is not usually what you want: fork clones all 2971fork-safe, their behaviour is not usually what you want: fork clones all
2951watchers, that means all timers, I/O watchers etc. are active in both 2972watchers, that means all timers, I/O watchers etc. are active in both
2952parent and child, which is almost never what you want. USing C<exec> 2973parent and child, which is almost never what you want. Using C<exec>
2953to start worker children from some kind of manage rprocess is usually 2974to start worker children from some kind of manage prrocess is usually
2954preferred, because it is much easier and cleaner, at the expense of having 2975preferred, because it is much easier and cleaner, at the expense of having
2955to have another binary. 2976to have another binary.
2977
2978In addition to logical problems with fork, there are also implementation
2979problems. For example, on POSIX systems, you cannot fork at all in Perl
2980code if a thread (I am talking of pthreads here) was ever created in the
2981process, and this is just the tip of the iceberg. In general, using fork
2982from Perl is difficult, and attempting to use fork without an exec to
2983implement some kind of parallel processing is almost certainly doomed.
2984
2985To safely fork and exec, you should use a module such as
2986L<Proc::FastSpawn> that let's you safely fork and exec new processes.
2987
2988If you want to do multiprocessing using processes, you can
2989look at the L<AnyEvent::Fork> module (and some related modules
2990such as L<AnyEvent::Fork::RPC>, L<AnyEvent::Fork::Pool> and
2991L<AnyEvent::Fork::Remote>). This module allows you to safely create
2992subprocesses without any limitations - you can use X11 toolkits or
2993AnyEvent in the children created by L<AnyEvent::Fork> safely and without
2994any special precautions.
2956 2995
2957 2996
2958=head1 SECURITY CONSIDERATIONS 2997=head1 SECURITY CONSIDERATIONS
2959 2998
2960AnyEvent can be forced to load any event model via 2999AnyEvent can be forced to load any event model via

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines