gpt4 book ai didi

延迟子上的 Perl AnyEvent 回调,如何异步运行它?

转载 作者:行者123 更新时间:2023-12-01 06:33:43 24 4
gpt4 key购买 nike

我开始学习 AnyEvent 并且遇到了一些麻烦。
我完全误解了如何获得异步利润 fe :

#!/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->recv将阻塞直到 ->send被称为,所以 do_delay()需要 $delay秒返回。

这是一个生成三个线程并等待所有线程完成的示例:

use strict;
use warnings;
use AnyEvent;

sub make_delay {
my ($name, $delay, $cv) = (@_);
$cv->begin;
return AE::timer $delay, 0, sub { warn "done with $name\n"; $cv->end };
}

my $cv = AE::cv;

my @timers = (make_delay("t1", 3, $cv),
make_delay("t2", 5, $cv),
make_delay("t3", 4, $cv)
);

$cv->recv;

关于延迟子上的 Perl AnyEvent 回调,如何异步运行它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6831368/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com