假设我在一个应用程序中有许多任务可以按任何顺序完成.当所有任务完成后,我需要运行一些代码.如果重要,应用程序在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 => );