Perl AnyEvent concurrency internals

350 Views Asked by At

I have a server, which creates a "AnyEvent timer" watcher object on every client connection (adds it to an AnyEvent loop).

use AnyEvent;

...

my $db_handle = myschema->connect();

my $w; $w = AnyEvent->timer (
       interval => $interval,
       after    => $interval,
       cb => sub {
          ## Remove from loop on some condition
          unless ( $ret = _check_session($sid) ) {
             undef $w;
          }

          ## Execute main logic
          $db_handle->lookup($sid);
       }
);

...

So the callback will be executed every $interval seconds. In case there are a lot of clients, some callbacks will have to be executed at the same time. How does AnyEvent handle this? Does it execute those callbacks one after another OR there is some concurrency mechanism in this case, so that those callbacks will be executed simultaneously? (for instance to speed up the execution of several callbacks that have to be executed at the same time by means of creating several threads)
In case of my server the callback performs database lookup. The database handle for the database connection has been initialized outside of event loop. My concern is that if there is any concurrency mechanism in AnyEvent, then the callbacks cannot be executed simultaneously because one callback has to wait until another one has finished database lookup and the database handle is free.
P.S. Thanks to 'ikegami' for the answer.

2

There are 2 best solutions below

0
On

As ikegami said - there's no concurrency in AnyEvent. Any event loop gives you the ability to handle events 'asynchronously' - so you can have multiple requests/operations/timers in progress simultaneously, without ever having concurrent code execution. Events are always handled sequentially.

For your specific case of multiple timers expiring at the same time - each timer is processed in turn (they are sorted on their expiry time), and all 'expired' timers are processed at each event loop iteration - e.g. lines 208-213 of Loop.pm for the pure Perl implementation which you can view @ CPAN.

0
On

AnyEvent does not create any concurrency. It processes events when you call into it (e.g. ->recv).