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.316 by root, Mon Mar 15 18:51:30 2010 UTC vs.
Revision 1.329 by root, Sun Jul 11 05:44:22 2010 UTC

7 7
8=head1 SYNOPSIS 8=head1 SYNOPSIS
9 9
10 use AnyEvent; 10 use AnyEvent;
11 11
12 # if you prefer function calls, look at the AE manpage for
13 # an alternative API.
14
12 # file descriptor readable 15 # file handle or descriptor readable
13 my $w = AnyEvent->io (fh => $fh, poll => "r", cb => sub { ... }); 16 my $w = AnyEvent->io (fh => $fh, poll => "r", cb => sub { ... });
14 17
15 # one-shot or repeating timers 18 # one-shot or repeating timers
16 my $w = AnyEvent->timer (after => $seconds, cb => sub { ... }); 19 my $w = AnyEvent->timer (after => $seconds, cb => sub { ... });
17 my $w = AnyEvent->timer (after => $seconds, interval => $seconds, cb => ... 20 my $w = AnyEvent->timer (after => $seconds, interval => $seconds, cb => ...
135 use AnyEvent; 138 use AnyEvent;
136 139
137 # .. AnyEvent will likely default to Tk 140 # .. AnyEvent will likely default to Tk
138 141
139The I<likely> means that, if any module loads another event model and 142The I<likely> means that, if any module loads another event model and
140starts using it, all bets are off. Maybe you should tell their authors to 143starts using it, all bets are off - this case should be very rare though,
141use AnyEvent so their modules work together with others seamlessly... 144as very few modules hardcode event loops without announcing this very
145loudly.
142 146
143The pure-perl implementation of AnyEvent is called 147The pure-perl implementation of AnyEvent is called
144C<AnyEvent::Impl::Perl>. Like other event modules you can load it 148C<AnyEvent::Impl::Perl>. Like other event modules you can load it
145explicitly and enjoy the high availability of that event loop :) 149explicitly and enjoy the high availability of that event loop :)
146 150
553will actively watch for new events and call your callbacks. 557will actively watch for new events and call your callbacks.
554 558
555AnyEvent is slightly different: it expects somebody else to run the event 559AnyEvent is slightly different: it expects somebody else to run the event
556loop and will only block when necessary (usually when told by the user). 560loop and will only block when necessary (usually when told by the user).
557 561
558The instrument to do that is called a "condition variable", so called 562The tool to do that is called a "condition variable", so called because
559because they represent a condition that must become true. 563they represent a condition that must become true.
560 564
561Now is probably a good time to look at the examples further below. 565Now is probably a good time to look at the examples further below.
562 566
563Condition variables can be created by calling the C<< AnyEvent->condvar 567Condition variables can be created by calling the C<< AnyEvent->condvar
564>> method, usually without arguments. The only argument pair allowed is 568>> method, usually without arguments. The only argument pair allowed is
569After creation, the condition variable is "false" until it becomes "true" 573After creation, the condition variable is "false" until it becomes "true"
570by calling the C<send> method (or calling the condition variable as if it 574by calling the C<send> method (or calling the condition variable as if it
571were a callback, read about the caveats in the description for the C<< 575were a callback, read about the caveats in the description for the C<<
572->send >> method). 576->send >> method).
573 577
574Condition variables are similar to callbacks, except that you can 578Since condition variables are the most complex part of the AnyEvent API, here are
575optionally wait for them. They can also be called merge points - points 579some different mental models of what they are - pick the ones you can connect to:
576in time where multiple outstanding events have been processed. And yet 580
577another way to call them is transactions - each condition variable can be 581=over 4
578used to represent a transaction, which finishes at some point and delivers 582
579a result. And yet some people know them as "futures" - a promise to 583=item * Condition variables are like callbacks - you can call them (and pass them instead
580compute/deliver something that you can wait for. 584of callbacks). Unlike callbacks however, you can also wait for them to be called.
585
586=item * Condition variables are signals - one side can emit or send them,
587the other side can wait for them, or install a handler that is called when
588the signal fires.
589
590=item * Condition variables are like "Merge Points" - points in your program
591where you merge multiple independent results/control flows into one.
592
593=item * Condition variables represent a transaction - function that start
594some kind of transaction can return them, leaving the caller the choice
595between waiting in a blocking fashion, or setting a callback.
596
597=item * Condition variables represent future values, or promises to deliver
598some result, long before the result is available.
599
600=back
581 601
582Condition variables are very useful to signal that something has finished, 602Condition variables are very useful to signal that something has finished,
583for example, if you write a module that does asynchronous http requests, 603for example, if you write a module that does asynchronous http requests,
584then a condition variable would be the ideal candidate to signal the 604then a condition variable would be the ideal candidate to signal the
585availability of results. The user can either act when the callback is 605availability of results. The user can either act when the callback is
606eventually calls C<< -> send >>, and the "consumer side", which waits 626eventually calls C<< -> send >>, and the "consumer side", which waits
607for the send to occur. 627for the send to occur.
608 628
609Example: wait for a timer. 629Example: wait for a timer.
610 630
611 # wait till the result is ready 631 # condition: "wait till the timer is fired"
612 my $result_ready = AnyEvent->condvar; 632 my $timer_fired = AnyEvent->condvar;
613 633
614 # do something such as adding a timer 634 # create the timer - we could wait for, say
615 # or socket watcher the calls $result_ready->send 635 # a handle becomign ready, or even an
616 # when the "result" is ready. 636 # AnyEvent::HTTP request to finish, but
617 # in this case, we simply use a timer: 637 # in this case, we simply use a timer:
618 my $w = AnyEvent->timer ( 638 my $w = AnyEvent->timer (
619 after => 1, 639 after => 1,
620 cb => sub { $result_ready->send }, 640 cb => sub { $timer_fired->send },
621 ); 641 );
622 642
623 # this "blocks" (while handling events) till the callback 643 # this "blocks" (while handling events) till the callback
624 # calls ->send 644 # calls ->send
625 $result_ready->recv; 645 $timer_fired->recv;
626 646
627Example: wait for a timer, but take advantage of the fact that condition 647Example: wait for a timer, but take advantage of the fact that condition
628variables are also callable directly. 648variables are also callable directly.
629 649
630 my $done = AnyEvent->condvar; 650 my $done = AnyEvent->condvar;
1054=head1 OTHER MODULES 1074=head1 OTHER MODULES
1055 1075
1056The following is a non-exhaustive list of additional modules that use 1076The following is a non-exhaustive list of additional modules that use
1057AnyEvent as a client and can therefore be mixed easily with other AnyEvent 1077AnyEvent as a client and can therefore be mixed easily with other AnyEvent
1058modules and other event loops in the same program. Some of the modules 1078modules and other event loops in the same program. Some of the modules
1059come with AnyEvent, most are available via CPAN. 1079come as part of AnyEvent, the others are available via CPAN.
1060 1080
1061=over 4 1081=over 4
1062 1082
1063=item L<AnyEvent::Util> 1083=item L<AnyEvent::Util>
1064 1084
1079 1099
1080=item L<AnyEvent::DNS> 1100=item L<AnyEvent::DNS>
1081 1101
1082Provides rich asynchronous DNS resolver capabilities. 1102Provides rich asynchronous DNS resolver capabilities.
1083 1103
1104=item L<AnyEvent::HTTP>, L<AnyEvent::IRC>, L<AnyEvent::XMPP>, L<AnyEvent::GPSD>, L<AnyEvent::IGS>, L<AnyEvent::FCP>
1105
1106Implement event-based interfaces to the protocols of the same name (for
1107the curious, IGS is the International Go Server and FCP is the Freenet
1108Client Protocol).
1109
1110=item L<AnyEvent::Handle::UDP>
1111
1112Here be danger!
1113
1114As Pauli would put it, "Not only is it not right, it's not even wrong!" -
1115there are so many things wrong with AnyEvent::Handle::UDP, most notably
1116it's use of a stream-based API with a protocol that isn't streamable, that
1117the only way to improve it is to delete it.
1118
1119It features data corruption (but typically only under load) and general
1120confusion. On top, the author is not only clueless about UDP but also
1121fact-resistant - some gems of his understanding: "connect doesn't work
1122with UDP", "UDP packets are not IP packets", "UDP only has datagrams, not
1123packets", "I don't need to implement proper error checking as UDP doesn't
1124support error checking" and so on - he doesn't even understand what's
1125wrong with his module when it is explained to him.
1126
1084=item L<AnyEvent::HTTP> 1127=item L<AnyEvent::DBI>
1085 1128
1086A simple-to-use HTTP library that is capable of making a lot of concurrent 1129Executes L<DBI> requests asynchronously in a proxy process for you,
1087HTTP requests. 1130notifying you in an event-bnased way when the operation is finished.
1131
1132=item L<AnyEvent::AIO>
1133
1134Truly asynchronous (as opposed to non-blocking) I/O, should be in the
1135toolbox of every event programmer. AnyEvent::AIO transparently fuses
1136L<IO::AIO> and AnyEvent together, giving AnyEvent access to event-based
1137file I/O, and much more.
1088 1138
1089=item L<AnyEvent::HTTPD> 1139=item L<AnyEvent::HTTPD>
1090 1140
1091Provides a simple web application server framework. 1141A simple embedded webserver.
1092 1142
1093=item L<AnyEvent::FastPing> 1143=item L<AnyEvent::FastPing>
1094 1144
1095The fastest ping in the west. 1145The fastest ping in the west.
1096
1097=item L<AnyEvent::DBI>
1098
1099Executes L<DBI> requests asynchronously in a proxy process.
1100
1101=item L<AnyEvent::AIO>
1102
1103Truly asynchronous I/O, should be in the toolbox of every event
1104programmer. AnyEvent::AIO transparently fuses L<IO::AIO> and AnyEvent
1105together.
1106
1107=item L<AnyEvent::BDB>
1108
1109Truly asynchronous Berkeley DB access. AnyEvent::BDB transparently fuses
1110L<BDB> and AnyEvent together.
1111
1112=item L<AnyEvent::GPSD>
1113
1114A non-blocking interface to gpsd, a daemon delivering GPS information.
1115
1116=item L<AnyEvent::IRC>
1117
1118AnyEvent based IRC client module family (replacing the older Net::IRC3).
1119
1120=item L<AnyEvent::XMPP>
1121
1122AnyEvent based XMPP (Jabber protocol) module family (replacing the older
1123Net::XMPP2>.
1124
1125=item L<AnyEvent::IGS>
1126
1127A non-blocking interface to the Internet Go Server protocol (used by
1128L<App::IGS>).
1129
1130=item L<Net::FCP>
1131
1132AnyEvent-based implementation of the Freenet Client Protocol, birthplace
1133of AnyEvent.
1134
1135=item L<Event::ExecFlow>
1136
1137High level API for event-based execution flow control.
1138 1146
1139=item L<Coro> 1147=item L<Coro>
1140 1148
1141Has special support for AnyEvent via L<Coro::AnyEvent>. 1149Has special support for AnyEvent via L<Coro::AnyEvent>.
1142 1150
1156 1164
1157BEGIN { AnyEvent::common_sense } 1165BEGIN { AnyEvent::common_sense }
1158 1166
1159use Carp (); 1167use Carp ();
1160 1168
1161our $VERSION = '5.251'; 1169our $VERSION = '5.271';
1162our $MODEL; 1170our $MODEL;
1163 1171
1164our $AUTOLOAD; 1172our $AUTOLOAD;
1165our @ISA; 1173our @ISA;
1166 1174
1169our $VERBOSE; 1177our $VERBOSE;
1170 1178
1171BEGIN { 1179BEGIN {
1172 require "AnyEvent/constants.pl"; 1180 require "AnyEvent/constants.pl";
1173 1181
1174 eval "sub TAINT (){" . (${^TAINT} *1) . "}"; 1182 eval "sub TAINT (){" . (${^TAINT}*1) . "}";
1175 1183
1176 delete @ENV{grep /^PERL_ANYEVENT_/, keys %ENV} 1184 delete @ENV{grep /^PERL_ANYEVENT_/, keys %ENV}
1177 if ${^TAINT}; 1185 if ${^TAINT};
1178 1186
1179 $VERBOSE = $ENV{PERL_ANYEVENT_VERBOSE}*1; 1187 $VERBOSE = $ENV{PERL_ANYEVENT_VERBOSE}*1;
1222our @post_detect; 1230our @post_detect;
1223 1231
1224sub post_detect(&) { 1232sub post_detect(&) {
1225 my ($cb) = @_; 1233 my ($cb) = @_;
1226 1234
1227 if ($MODEL) {
1228 $cb->();
1229
1230 undef
1231 } else {
1232 push @post_detect, $cb; 1235 push @post_detect, $cb;
1233 1236
1234 defined wantarray 1237 defined wantarray
1235 ? bless \$cb, "AnyEvent::Util::postdetect" 1238 ? bless \$cb, "AnyEvent::Util::postdetect"
1236 : () 1239 : ()
1237 }
1238} 1240}
1239 1241
1240sub AnyEvent::Util::postdetect::DESTROY { 1242sub AnyEvent::Util::postdetect::DESTROY {
1241 @post_detect = grep $_ != ${$_[0]}, @post_detect; 1243 @post_detect = grep $_ != ${$_[0]}, @post_detect;
1242} 1244}
1295 @models = (); # free probe data 1297 @models = (); # free probe data
1296 1298
1297 push @{"$MODEL\::ISA"}, "AnyEvent::Base"; 1299 push @{"$MODEL\::ISA"}, "AnyEvent::Base";
1298 unshift @ISA, $MODEL; 1300 unshift @ISA, $MODEL;
1299 1301
1302 # now nuke some methods that are overriden by the backend.
1303 # SUPER is not allowed.
1304 for (qw(time signal child idle)) {
1305 undef &{"AnyEvent::Base::$_"}
1306 if defined &{"$MODEL\::$_"};
1307 }
1308
1300 require AnyEvent::Strict if $ENV{PERL_ANYEVENT_STRICT}; 1309 require AnyEvent::Strict if $ENV{PERL_ANYEVENT_STRICT};
1301 1310
1302 (shift @post_detect)->() while @post_detect; 1311 (shift @post_detect)->() while @post_detect;
1312
1313 *post_detect = sub(&) {
1314 shift->();
1315
1316 undef
1317 };
1303 1318
1304 $MODEL 1319 $MODEL
1305} 1320}
1306 1321
1307sub AUTOLOAD { 1322sub AUTOLOAD {
1335 1350
1336=head1 SIMPLIFIED AE API 1351=head1 SIMPLIFIED AE API
1337 1352
1338Starting with version 5.0, AnyEvent officially supports a second, much 1353Starting with version 5.0, AnyEvent officially supports a second, much
1339simpler, API that is designed to reduce the calling, typing and memory 1354simpler, API that is designed to reduce the calling, typing and memory
1340overhead. 1355overhead by using function call syntax and a fixed number of parameters.
1341 1356
1342See the L<AE> manpage for details. 1357See the L<AE> manpage for details.
1343 1358
1344=cut 1359=cut
1345 1360
1346package AE; 1361package AE;
1347 1362
1348our $VERSION = $AnyEvent::VERSION; 1363our $VERSION = $AnyEvent::VERSION;
1364
1365# fall back to the main API by default - backends and AnyEvent::Base
1366# implementations can overwrite these.
1349 1367
1350sub io($$$) { 1368sub io($$$) {
1351 AnyEvent->io (fh => $_[0], poll => $_[1] ? "w" : "r", cb => $_[2]) 1369 AnyEvent->io (fh => $_[0], poll => $_[1] ? "w" : "r", cb => $_[2])
1352} 1370}
1353 1371
1385 1403
1386package AnyEvent::Base; 1404package AnyEvent::Base;
1387 1405
1388# default implementations for many methods 1406# default implementations for many methods
1389 1407
1390sub _time() { 1408sub time {
1391 eval q{ # poor man's autoloading 1409 eval q{ # poor man's autoloading {}
1392 # probe for availability of Time::HiRes 1410 # probe for availability of Time::HiRes
1393 if (eval "use Time::HiRes (); Time::HiRes::time (); 1") { 1411 if (eval "use Time::HiRes (); Time::HiRes::time (); 1") {
1394 warn "AnyEvent: using Time::HiRes for sub-second timing accuracy.\n" if $VERBOSE >= 8; 1412 warn "AnyEvent: using Time::HiRes for sub-second timing accuracy.\n" if $VERBOSE >= 8;
1395 *_time = \&Time::HiRes::time; 1413 *AE::time = \&Time::HiRes::time;
1396 # if (eval "use POSIX (); (POSIX::times())... 1414 # if (eval "use POSIX (); (POSIX::times())...
1397 } else { 1415 } else {
1398 warn "AnyEvent: using built-in time(), WARNING, no sub-second resolution!\n" if $VERBOSE; 1416 warn "AnyEvent: using built-in time(), WARNING, no sub-second resolution!\n" if $VERBOSE;
1399 *_time = sub (){ time }; # epic fail 1417 *AE::time = sub (){ time }; # epic fail
1400 } 1418 }
1419
1420 *time = sub { AE::time }; # different prototypes
1401 }; 1421 };
1402 die if $@; 1422 die if $@;
1403 1423
1404 &_time 1424 &time
1405} 1425}
1406 1426
1407sub time { _time } 1427*now = \&time;
1408sub now { _time } 1428
1409sub now_update { } 1429sub now_update { }
1410 1430
1411# default implementation for ->condvar 1431# default implementation for ->condvar
1412 1432
1413sub condvar { 1433sub condvar {
1434 eval q{ # poor man's autoloading {}
1435 *condvar = sub {
1414 bless { @_ == 3 ? (_ae_cb => $_[2]) : () }, "AnyEvent::CondVar" 1436 bless { @_ == 3 ? (_ae_cb => $_[2]) : () }, "AnyEvent::CondVar"
1437 };
1438
1439 *AE::cv = sub (;&) {
1440 bless { @_ ? (_ae_cb => shift) : () }, "AnyEvent::CondVar"
1441 };
1442 };
1443 die if $@;
1444
1445 &condvar
1415} 1446}
1416 1447
1417# default implementation for ->signal 1448# default implementation for ->signal
1418 1449
1419our $HAVE_ASYNC_INTERRUPT; 1450our $HAVE_ASYNC_INTERRUPT;
1449 undef $SIG_TW 1480 undef $SIG_TW
1450 unless --$SIG_COUNT; 1481 unless --$SIG_COUNT;
1451} 1482}
1452 1483
1453our $_sig_name_init; $_sig_name_init = sub { 1484our $_sig_name_init; $_sig_name_init = sub {
1454 eval q{ # poor man's autoloading 1485 eval q{ # poor man's autoloading {}
1455 undef $_sig_name_init; 1486 undef $_sig_name_init;
1456 1487
1457 if (_have_async_interrupt) { 1488 if (_have_async_interrupt) {
1458 *sig2num = \&Async::Interrupt::sig2num; 1489 *sig2num = \&Async::Interrupt::sig2num;
1459 *sig2name = \&Async::Interrupt::sig2name; 1490 *sig2name = \&Async::Interrupt::sig2name;
1513 or Carp::croak "AnyEvent: unable to create a signal reporting pipe: $!\n"; 1544 or Carp::croak "AnyEvent: unable to create a signal reporting pipe: $!\n";
1514 1545
1515 $SIG_IO = AE::io $SIGPIPE_R, 0, \&_signal_exec; 1546 $SIG_IO = AE::io $SIGPIPE_R, 0, \&_signal_exec;
1516 } 1547 }
1517 1548
1518 *signal = sub { 1549 *signal = $HAVE_ASYNC_INTERRUPT
1550 ? sub {
1519 my (undef, %arg) = @_; 1551 my (undef, %arg) = @_;
1520 1552
1521 my $signal = uc $arg{signal}
1522 or Carp::croak "required option 'signal' is missing";
1523
1524 if ($HAVE_ASYNC_INTERRUPT) {
1525 # async::interrupt 1553 # async::interrupt
1526
1527 $signal = sig2num $signal; 1554 my $signal = sig2num $arg{signal};
1528 $SIG_CB{$signal}{$arg{cb}} = $arg{cb}; 1555 $SIG_CB{$signal}{$arg{cb}} = $arg{cb};
1529 1556
1530 $SIG_ASY{$signal} ||= new Async::Interrupt 1557 $SIG_ASY{$signal} ||= new Async::Interrupt
1531 cb => sub { undef $SIG_EV{$signal} }, 1558 cb => sub { undef $SIG_EV{$signal} },
1532 signal => $signal, 1559 signal => $signal,
1533 pipe => [$SIGPIPE_R->filenos], 1560 pipe => [$SIGPIPE_R->filenos],
1534 pipe_autodrain => 0, 1561 pipe_autodrain => 0,
1535 ; 1562 ;
1536 1563
1537 } else { 1564 bless [$signal, $arg{cb}], "AnyEvent::Base::signal"
1565 }
1566 : sub {
1567 my (undef, %arg) = @_;
1568
1538 # pure perl 1569 # pure perl
1539
1540 # AE::Util has been loaded in signal
1541 $signal = sig2name $signal; 1570 my $signal = sig2name $arg{signal};
1542 $SIG_CB{$signal}{$arg{cb}} = $arg{cb}; 1571 $SIG_CB{$signal}{$arg{cb}} = $arg{cb};
1543 1572
1544 $SIG{$signal} ||= sub { 1573 $SIG{$signal} ||= sub {
1545 local $!; 1574 local $!;
1546 syswrite $SIGPIPE_W, "\x00", 1 unless %SIG_EV; 1575 syswrite $SIGPIPE_W, "\x00", 1 unless %SIG_EV;
1547 undef $SIG_EV{$signal}; 1576 undef $SIG_EV{$signal};
1548 }; 1577 };
1549 1578
1550 # can't do signal processing without introducing races in pure perl, 1579 # can't do signal processing without introducing races in pure perl,
1551 # so limit the signal latency. 1580 # so limit the signal latency.
1552 _sig_add; 1581 _sig_add;
1553 }
1554 1582
1555 bless [$signal, $arg{cb}], "AnyEvent::Base::signal" 1583 bless [$signal, $arg{cb}], "AnyEvent::Base::signal"
1584 }
1556 }; 1585 ;
1557 1586
1558 *AnyEvent::Base::signal::DESTROY = sub { 1587 *AnyEvent::Base::signal::DESTROY = sub {
1559 my ($signal, $cb) = @{$_[0]}; 1588 my ($signal, $cb) = @{$_[0]};
1560 1589
1561 _sig_del; 1590 _sig_del;
2057 2086
2058The actual code goes further and collects all errors (C<die>s, exceptions) 2087The actual code goes further and collects all errors (C<die>s, exceptions)
2059that occurred during request processing. The C<result> method detects 2088that occurred during request processing. The C<result> method detects
2060whether an exception as thrown (it is stored inside the $txn object) 2089whether an exception as thrown (it is stored inside the $txn object)
2061and just throws the exception, which means connection errors and other 2090and just throws the exception, which means connection errors and other
2062problems get reported tot he code that tries to use the result, not in a 2091problems get reported to the code that tries to use the result, not in a
2063random callback. 2092random callback.
2064 2093
2065All of this enables the following usage styles: 2094All of this enables the following usage styles:
2066 2095
20671. Blocking: 20961. Blocking:

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines