Consider the code below, where CPU crunching is done when Event loop is idle, but only for 0.1s to allow HTTP requests about the processed data to not be delayed more than ~100mS.
Is there any better way to do this that would eliminate the (up-to) 100mS wait time for a request to actioned? Basically... is there any way idle could run continously and be interuptted by the events? What is generally used in this situation. A second thread?
Thanks!
use strict;
use warnings;
use AnyEvent;
use AnyEvent::HTTPD;
use Time::HiRes qw(gettimeofday);
use Digest::MD5 qw(md5);
my $httpd = AnyEvent::HTTPD->new(port=>9090);
my $count = 0;
my $foo = 'bar';
# Handle other events
$httpd->reg_cb(
'/count' => sub {
my ($h,$r)= @_;
$r->respond({content=>['text/plain',"$count: ".(unpack 'q',$fo
+o)]});
$h->stop_request;
});
# CPU crunching for 100mS when idle...
my $idle = AnyEvent->idle(cb => sub {
my $now = gettimeofday;
while(gettimeofday < ($now + 0.1)) { $foo = md5($foo); }
$count+=1;
});
my $cv = AnyEvent->condvar;
$cv->recv;