perl – 复用回调

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

在某种程度上,AnyEvent的$cv-> begin / $cv-> end允许我想要的.不过,我想要更细致的控制.例如,我想无法“完成”任务两次.从所有任务收集数据的能力也是不错的.

当然可以做到这一点.设置大量共享哈希的回调;每当任务完成时,从该哈希删除密钥;当哈希为空时,调用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 => );

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...