3
AnyEvent::FAQ - frequently asked questions
5
The newest version of this document can be found at
6
L<http://pod.tst.eu/http://cvs.schmorp.de/AnyEvent/lib/AnyEvent/FAQ.pod>.
8
=head2 My program exits before doing anything, what's going on?
10
Programmers new to event-based programming often forget that you can
11
actually do other stuff while "waiting" for an event to occur and
12
therefore forget to actually wait when they do not, in fact, have anything
19
my $timer = AnyEvent->timer (after => 5, cb => sub { say "hi" });
21
The expectation might be for the program to print "hi" after 5 seconds
22
and then probably to exit. However, if you run this, your program will
23
exit almost instantly: Creating the timer does not wait for it, instead
24
the C<timer> method returns immediately and perl executes the rest of the
25
program. But there is nothing left to execute, so perl exits.
27
To force AnyEvent to wait for something, use a condvar:
31
my $quit_program = AnyEvent->condvar;
32
my $timer = AnyEvent->timer (after => 5, cb => sub { $quit_program->send });
36
Here the program doesn't immediately exit, because it first waits for
37
the "quit_program" condition.
39
In most cases, your main program should call the event library "loop"
49
=head2 Why is my C<tcp_connect> callback never called?
51
Tricky: C<tcp_connect> (and a few other functions in L<AnyEvent::Socket>)
52
is critically sensitive to the caller context.
54
In void context, it will just do it's thing and eventually call the
55
callback. In any other context, however, it will return a special "guard"
56
object - when it is destroyed (e.g. when you don't store it but throw it
57
away), tcp_connect will no longer try to connect or call any callbacks.
59
Often this happens when the C<tcp_connect> call is at the end of a function:
62
tcp_connect "www.example.com", 80, sub {
67
Then the caller decides whether there is a void context or not. One can
68
avoid these cases by explicitly returning nothing:
71
tcp_connect "www.example.com", 80, sub {
78
=head2 Why do some backends use a lot of CPU in C<< AE::cv->recv >>?
80
Many people try out this simple program, or it's equivalent:
82
AnyEvent->condvar->recv;
84
They are then shocked to see that this basically idles with the Perl
85
backend, but uses 100% CPU with the EV backend, which is supposed to be
88
The key to understand this is to understand that the above program is
89
actually buggy: Nothing calls C<< ->send >> on the condvar, ever. Worse,
90
there are no event watchers whatsoever. Basically, it creates a deadlock:
91
there is no way to make progress.
93
Some backends handle this by freezing, some by idling, and some do a 100%
96
Since this program is nonsensical (and behaves as documented with all
97
backends, as AnyEvent makes no CPU tikme guarantees), this shouldn't be a
98
big deal - as soon as your program actually implements something sensible,
99
CPU usage will be normal.
103
Marc Lehmann <schmorp@schmorp.de>.