AnyEvent with Coro, AKA async TCP daemon.

Antti Linno sihker at hot.ee
Thu Aug 1 15:57:59 CEST 2013


Good day.

I'm trying to build a simple non-blocking TCP daemon. If I need HTTP 
daemon, should I use Twiggy?

This is what I have so far:

use Modern::Perl '2012';
use EV;
use AnyEvent::Socket;
use Coro;

sub start_thread($$$$) {
     my ( $time, $fh, $host, $port ) = @_;
     return async {
         say "Starting sleep of $time, $host, $port";
         sleep $time;
         say "Done sleeping!";
     };
}

AnyEvent::Socket::tcp_server undef, 11211, sub {
   my ( $fh, $host, $port ) = @_;

   start_thread 20, $fh, $host, $port;
   }, sub {
   my ( $fh, $thishost, $thisport ) = @_;
   AE::log info => "Bound to $thishost, port $thisport.";
   };

EV::loop;

The problem is, this solution is blocking. If I make two requests, then 
the second one is pending, while the first one sleeps.

I could fork

sub start_thread($$$$) {
     my ( $time, $fh, $host, $port ) = @_;
     if ( my $pid = fork ) {
         say "Starting sleep of $time, $host, $port";
         sleep 20;
         say "Done sleeping!";
     };
}

This is not blocking, but is this the optimal way? How to do it with Coro?

Greetings,
Antti



More information about the anyevent mailing list