perl - 多路复用回调

标签 perl asynchronous

假设我在一个应用程序中有许多任务可以按任何顺序完成。当所有任务完成后,我需要运行一些代码。如果这很重要,应用程序在 AnyEvent 下运行,但没有 Coro。

在某种程度上,AnyEvent$cv->begin/$cv->end允许我想要的。但是,我希望有更细粒度的控制。例如,我希望不能两次“完成”一项任务。从所有任务中收集数据的能力也很好。

当然,这是可以做到的。设置许多共享哈希的回调;每当任务完成时从该哈希中删除键;当 hash 为空时调用 megacallback。我想知道是否有更文明的方法,也许是一些 CPAN 模块?

例如,这是一个可以满足我需要的虚构 API。

#!/usr/bin/perl -w 
use strict;

use Some::Module;

# Set goals
my $cb = Some::Module->new( sub { say 'BOOM!' } );
$cb->begin( qw(foo bar) );

# Much later, as tasks start getting done
$cb->end( foo => 42 );       # "return" value from task 'foo'
$cb->begin( 'baz' );         # can add more tasks, why not
$cb->end( 'bar' );           # just finish task 'bar'
# still waiting for 'baz' to finish at this point

# Finally, last hanging task is done
$cb->end( baz => 137 );      # BOOM!
# at this point, sub {}->( { foo=>42, bar=>undef, baz=>137 } ) 
#     has been called

另见我的perlmonks question .

它有这样的东西吗?

最佳答案

您可能要考虑 Future .

具体来说,要等待许多事情完成,您可以使用 Future->needs_all或类似的:

my @things = ... # generate Futures to represent each thing

Future->needs_all( @things )
  ->on_done( sub {
     # some code here when all the things are done 
  });

或者,您也可以尝试 Async::MergePoint这使 API 更接近您的想法:
my $mp = Async::MergePoint->new( needs => [qw( foo bar )] );
$mp->close( on_done => sub {
   # some code here when all the things are done
});

$mp->done( foo => $value );
$mp->done( bar => );

关于perl - 多路复用回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15832405/

相关文章:

javascript - 当我在一个页面上有多个 Like 按钮时,有没有办法防止同一个 JS/CSS 文件被多次加载?

node.js - NodeJS - 强制用户等待全局事件完成

perl - 如何使用 'subroutine reference' 作为哈希键

perl - 如何将哈希插入到 Perl 中的哈希中

arrays - Perl Moose 对象可以直接具有数组/哈希属性吗?

regex - Perl 正则表达式否定回顾

asynchronous - 未处理的异常Future dynamic不是FutureOr List Books类型的子类型

ios - ImageView 导致尴尬的挂起?

Perl:通过转换为秒来计算天数

asynchronous - 立即解决 Observable - 相当于 $q.when()