The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

CPS::Future - represent an operation awaiting completion

SYNOPSIS

 my $future = CPS::Future->new;
 $future->on_ready( sub {
    say "The operation is complete";
 } );

 kperform_some_operation( sub {
    $future->done( @_ );
 } );

DESCRIPTION

An CPS::Future object represents an operation that is currently in progress, or has recently completed. It can be used in a variety of ways to manage the flow of control, and data, through an asynchronous program.

Some futures represent a single operation (returned by the new constructor), and are explicitly marked as complete by calling the done method. Others represent a tree of sub-tasks (returned by the wait_all constructor), and are implicitly marked as complete when all of their component futures are complete.

It is intended that library functions that perform asynchonous operations would use CPS::Future objects to represent outstanding operations, and allow their calling programs to control or wait for these operations to complete.

CONSTRUCTORS

$future = CPS::Future->new

Returns a new CPS::Future instance to represent a leaf future. It will be marked as complete by either of the done or fail methods.

$future = CPS::Future->wait_all( @subfutures )

Returns a new CPS::Future instance that will indicate completion once all of the sub future objects given to it indicate that they are complete.

METHODS

$ready = $future->is_ready

Returns true on a leaf future if a result has been provided to the done method or failed using the fail method, true on a wait_all future if all the sub-tasks are ready, or false if it is still waiting.

$future->on_ready( $code )

If the future is not yet ready, adds a callback to be invoked when the future is ready. If the future is already ready, invokes it immediately.

In either case, the callback will be passed the future object itself. The invoked code can then obtain the list of results by calling the get method.

 $on_ready->( $future )

$future->done( @result )

Marks that the leaf future is now complete, and provides a list of values as a result. (The empty list is allowed, and still indicates the future as complete). Cannot be called on a wait_all future.

$task->fail( $exception )

Marks that the leaf future has failed, and provides an exception value. This exception will be thrown by the get method if called. If the exception is a non-reference that does not end in a linefeed, its value will be extended by the file and line number of the caller, similar to the logic that die uses.

The exception must evaluate as a true value; false exceptions are not allowed.

@result = $future->get

If the future is complete, returns the list of results that had earlier been given to the done method. If not, will raise an exception.

If called on a wait_all future, it will return a list of the futures it was waiting on, in the order they were passed to the constructor.

$exception = $task->failure

Returns the exception passed to the fail method, undef if the task completed successfully via the done method, or raises an exception if called on a task that is not yet complete.

Because the exception value must be true, this can be used in a simple if statement:

 if( my $exception = $task->failure ) {
    ...
 }
 else {
    my @result = $task->get;
    ...
 }

EXAMPLES

The following examples all demonstrate possible uses of a CPS::Future object to provide a fictional asynchronous API function called simply koperation.

Providing Results

By returning a new CPS::Future object each time the asynchronous function is called, it provides a placeholder for its eventual result, and a way to indicate when it is complete.

 sub koperation
 {
    my %args = @_;

    my $future = CPS::Future->new;

    kdo_something(
       foo => $args{foo},
       on_done => sub { $future->done( @_ ); },
    );
 }

The caller may then use this future to wait for a result using the on_ready method, and obtain the result using get.

 my $f = koperation( foo => "something" );

 $f->on_ready( sub {
    my $f = shift;
    say "The operation returned: ", $f->get;
 } );

Indicating Success or Failure

Because the stored exception value of a failued CPS::Future may not be false, the failure method can be used in a conditional statement to detect success or failure.

 my $f = koperation( foo => "something" );

 $f->on_ready( sub {
    my $f = shift;
    if( not my $e = $f->failure ) {
       say "The operation succeeded with: ", $f->get;
    }
    else {
       say "The operation failed with: ", $e;
    }
 } );

By using not in the condition, the order of the if blocks can be arranged to put the successful case first, similar to a try/catch block.

Because the get method re-raises the passed exception if the future failed, it can be used to control a try/catch block directly. (This is sometimes called Exception Hoisting).

 use Try::Tiny;

 $f->on_ready( sub {
    my $f = shift;
    try {
       say "The operation succeeded with: ", $f->get;
    }
    catch {
       say "The operation failed with: ", $_;
    };
 } );

Merging Control Flow

A wait_all future may be used to resynchronise control flow, while waiting for multiple concurrent operations to finish.

 my $f1 = koperation( foo => "something" );
 my $f2 = koperation( bar => "something else" );

 my $f = CPS::Future->wait_all( $f1, $f2 );

 $f->on_ready( sub {
    say "Operations are ready:";
    say "  foo: ", $f1->get;
    say "  bar: ", $f2->get;
 } );

This provides an ability somewhat similar to CPS::kpar() or Async::MergePoint.

TODO

Lots of things still need adding. API or semantics is somewhat unclear in places.

  • Allow futures to be cancellable. Give them a cancel method, and some way to hook code to run to cancel it. Should the canceller blocks accumulate, or replace each other?

  • CPS::Future->needs_all, which fails on the first failure of dependent futures and cancels the outstanding ones.

  • CPS::Future->needs_first, which succeeds on the first success of dependent futures and cancels the outstanding ones, only fails if all the dependents do.

  • Some way to do deferred futures that don't even start their operation until invoked somehow. Ability to chain these together in a sequence, like CPS::kseq().

AUTHOR

Paul Evans <leonerd@leonerd.org.uk>