perl - Multiplexing callbacks -
suppose have number of tasks in 1 application may finish in order. , need run code when of tasks have finished. if matters, application running under anyevent, without coro.
to extent, anyevent's $cv->begin/$cv->end
allow want. however, i'd have more fine-grained control. instance, i'd unable "finish" task twice. ability gather data tasks nice.
of course, can done. set lots of callbacks share hash; delete keys hash whenever task finishes; call megacallback when hash empty. wonder if there's more civilized way of doing it, maybe cpan module?
for instance, here's imaginary api fill need.
#!/usr/bin/perl -w use strict; use some::module; # set goals $cb = some::module->new( sub { 'boom!' } ); $cb->begin( qw(foo bar) ); # later, tasks start getting done $cb->end( foo => 42 ); # "return" value task 'foo' $cb->begin( 'baz' ); # can add more tasks, why not $cb->end( 'bar' ); # finish task 'bar' # still waiting 'baz' finish @ point # finally, last hanging task done $cb->end( baz => 137 ); # boom! # @ point, sub {}->( { foo=>42, bar=>undef, baz=>137 } ) # has been called
see perlmonks question.
it there this?
you might want consider future.
specifically, waiting on many things complete, can use future->needs_all
or similar:
my @things = ... # generate futures represent each thing future->needs_all( @things ) ->on_done( sub { # code here when things done });
alternatively, try async::mergepoint gives api closer had in mind:
my $mp = async::mergepoint->new( needs => [qw( foo bar )] ); $mp->close( on_done => sub { # code here when things done }); $mp->done( foo => $value ); $mp->done( bar => );
Comments
Post a Comment