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