Acme-Sort-Sleep
view release on metacpan or search on metacpan
local/lib/perl5/Future/Phrasebook.pod view on Meta::CPAN
Another variation is the C<try_repeat_until_success> function, which provides
a convenient shortcut to calling C<try_repeat> with a condition that makes
another attempt each time the previous one fails; stopping once it achieves a
successful result.
while(1) {
eval { TRIAL(); 1 } and last;
}
Z<>
my $f = try_repeat_until_success {
F_TRIAL();
};
=head2 Iterating over a List
A variation on the idea of the C<while> loop is the C<foreach> loop; a loop
that executes once for each item in a given list, with a variable set to one
value from that list each time.
foreach my $thing ( @THINGS ) {
INSPECT( $thing );
}
This can be performed with C<Future> using the C<foreach> parameter to the
C<repeat> function. When this is in effect, the block of code is passed each
item of the given list as the first parameter.
my $f = repeat {
my $thing = shift;
F_INSPECT( $thing );
} foreach => \@THINGS;
=head2 Recursing over a Tree
A regular call/return function can use recursion to walk over a tree-shaped
structure, where each item yields a list of child items.
sub WALK
{
my ( $item ) = @_;
...
WALK($_) foreach CHILDREN($item);
}
This recursive structure can be turned into a C<while()>-based repeat loop by
using an array to store the remaining items to walk into, instead of using the
perl stack directly:
sub WALK
{
my @more = ( $root );
while( @more ) {
my $item = shift @more;
...
unshift @more, CHILDREN($item)
}
}
This arrangement then allows us to use C<fmap_void> to walk this structure
using Futures, possibly concurrently. A lexical array variable is captured
that holds the stack of remaining items, which is captured by the item code so
it can C<unshift> more into it, while also being used as the actual C<fmap>
control array.
my @more = ( $root );
my $f = fmap_void {
my $item = shift;
...->on_done( sub {
unshift @more, @CHILDREN;
})
} foreach => \@more;
By choosing to either C<unshift> or C<push> more items onto this list, the
tree can be walked in either depth-first or breadth-first order.
=head1 SHORT-CIRCUITING
Sometimes a result is determined that should be returned through several
levels of control structure. Regular Perl code has such keywords as C<return>
to return a value from a function immediately, or C<last> for immediately
stopping execution of a loop.
sub func {
foreach my $item ( @LIST ) {
if( COND($item) ) {
return $item;
}
}
return MAKE_NEW_ITEM();
}
The C<Future::Utils::call_with_escape> function allows this general form of
control flow, by calling a block of code that is expected to return a future,
and itself returning a future. Under normal circumstances the result of this
future propagates through to the one returned by C<call_with_escape>.
However, the code is also passed in a future value, called here the "escape
future". If the code captures this future and completes it (either by calling
C<done> or C<fail>), then the overall returned future immediately completes
with that result instead, and the future returned by the code block is
cancelled.
my $f = call_with_escape {
my $escape_f = shift;
( repeat {
my $item = shift;
COND($item)->then( sub {
my ( $result ) = @_;
if( $result ) {
$escape_f->done( $item );
}
return Future->done;
})
} foreach => \@ITEMS )->then( sub {
MAKE_NEW_ITEM();
});
};
Here, if C<$escape_f> is completed by the condition test, the future chain
returned by the code (that is, the C<then> chain of the C<repeat> block
followed by C<MAKE_NEW_ITEM()>) will be cancelled, and C<$f> itself will
receive this result.
=head1 CONCURRENCY
This final section of the phrasebook demonstrates a number of abilities that
are simple to do with C<Future> but can't easily be done with regular
call/return style programming, because they all involve an element of
concurrency. In these examples the comparison with regular call/return code
will be somewhat less accurate because of the inherent ability for the
C<Future>-using version to behave concurrently.
=head2 Waiting on Multiple Functions
The C<< Future->wait_all >> constructor creates a C<Future> that waits for all
of the component futures to complete. This can be used to form a sequence with
concurrency.
{ FIRST_A(); FIRST_B() }
SECOND();
Z<>
my $f = Future->wait_all( FIRST_A(), FIRST_B() )
->then( sub { SECOND() } );
Unlike in the call/return case, this can perform the work of C<FIRST_A()> and
C<FIRST_B()> concurrently, only proceeding to C<SECOND()> when both are ready.
The result of the C<wait_all> C<Future> is the list of its component
C<Future>s. This can be used to obtain the results.
SECOND( FIRST_A(), FIRST_B() );
Z<>
my $f = Future->wait_all( FIRST_A(), FIRST_B() )
->then( sub {
my ( $f_a, $f_b ) = @_
SECOND( $f_a->get, $f_b->get );
} );
Because the C<get> method will re-raise an exception caused by a failure of
either of the C<FIRST> functions, the second stage will fail if any of the
initial Futures failed.
As this is likely to be the desired behaviour most of the time, this kind of
control flow can be written slightly neater using C<< Future->needs_all >>
instead.
my $f = Future->needs_all( FIRST_A(), FIRST_B() )
->then( sub { SECOND( @_ ) } );
The C<get> method of a C<needs_all> convergent Future returns a concatenated
list of the results of all its component Futures, as the only way it will
succeed is if all the components do.
=head2 Waiting on Multiple Calls of One Function
Because the C<wait_all> and C<needs_all> constructors take an entire list of
C<Future> instances, they can be conveniently used with C<map> to wait on the
result of calling a function concurrently once per item in a list.
my @RESULT = map { FUNC( $_ ) } @ITEMS;
PROCESS( @RESULT );
Again, the C<needs_all> version allows more convenient access to the list of
results.
my $f = Future->needs_all( map { F_FUNC( $_ ) } @ITEMS )
->then( sub {
my @RESULT = @_;
F_PROCESS( @RESULT )
} );
This form of the code starts every item's future concurrently, then waits for
all of them. If the list of C<@ITEMS> is potentially large, this may cause a
problem due to too many items running at once. Instead, the
C<Future::Utils::fmap> family of functions can be used to bound the
concurrency, keeping at most some given number of items running, starting new
ones as existing ones complete.
my $f = fmap {
my $item = shift;
F_FUNC( $item )
} foreach => \@ITEMS;
By itself, this will not actually act concurrently as it will only keep one
Future outstanding at a time. The C<concurrent> flag lets it keep a larger
number "in flight" at any one time:
my $f = fmap {
my $item = shift;
F_FUNC( $item )
} foreach => \@ITEMS, concurrent => 10;
The C<fmap> and C<fmap_scalar> functions return a Future that will eventually
give the collected results of the individual item futures, thus making them
similar to perl's C<map> operator.
Sometimes, no result is required, and the items are run in a loop simply for
some side-effect of the body.
foreach my $item ( @ITEMS ) {
FUNC( $item );
}
To avoid having to collect a potentially-large set of results only to throw
them away, the C<fmap_void> function variant of the C<fmap> family yields a
Future that completes with no result after all the items are complete.
my $f = fmap_void {
my $item = shift;
F_FIRST( $item )
} foreach => \@ITEMS, concurrent => 10;
=head1 AUTHOR
Paul Evans <leonerd@leonerd.org.uk>
=cut
( run in 1.337 second using v1.01-cache-2.11-cpan-d8267643d1d )