我開始學習AnyEvent,並有一些與它的事情。 我完全誤解了怎麼它可能獲得異步利潤,FE:Perl延遲子上的AnyEvent回調,如何運行它的異步?
#!/usr/bin/env perl
package LatencySub;
use strict;
use warnings;
use AnyEvent;
# sub for emulate latency - is it right way?
sub do_delay{
my ($name, $delay) = (@_);
my $cv = AE::cv;
my $timer = AE::timer $delay, 0, sub { $cv->send() };
$cv->recv;
return $name.' proceed, delay is '.$delay;
};
package main;
use 5.12.0;
use warnings;
use Smart::Comments;
use AnyEvent;
my @list = (
{ name => 'first', delay => 1 },
{ name => 'second', delay => 1 },
{ name => 'third', delay => 2 }
);
sub process_cb {
my ($name, $delay, $cb) = @_;
my $result = LatencySub::do_delay($name, $delay);
$cb->($result);
}
my %result;
my $cv = AE::cv;
# outer loop
$cv->begin (sub { shift->send (\%result) });
my $before_time = AE::time;
### foreach start...
foreach my $entity (@list) {
$cv->begin;
process_cb (
$entity->{'name'},
$entity->{'delay'},
sub {
$result{$entity->{'name'}} = shift;
$cv->end;
}
);
}
### foreach end...
$cv->end;
my $time_all = AE::time - $before_time;
### $time_all
### %result
在輸出我:
### foreach start...
### foreach end...
### $time_all: '4.02105116844177'
### %result: {
### first => 'first proceed, delay is 1',
### second => 'second proceed, delay is 1',
### third => 'third proceed, delay is 2'
### }
所有的延遲總和(1 + 1 + 2)EQ $ time_all - 4秒。 所以,根本沒有利潤。
爲什麼它,我怎麼可以(和有可能?)創建「正確的」回調?
啊哈!這更像是我想要的。 「$ cv-> begin; my $ timer = AE :: timer $ delay,0,sub {warn」done with $ name \ n「; $ cv-> end};我認爲它非常重要。返回$ timer;「 (只是爲了簡單查看)返回AE :: timer對象? – Meettya
請參閱perldoc AnyEvent中$ cv-> begin的文檔。 $ cv-> begin遞增計數器,$ cv-> end遞減計數器並在計數器達到0時觸發條件變量。 此外,您還需要保存AE :: timer對象,以便它們不會超出範圍。 – perlman