Acme-Sort-Sleep
view release on metacpan or search on metacpan
local/lib/perl5/IO/Async/Function.pm view on Meta::CPAN
package IO::Async::Function;
use strict;
use warnings;
our $VERSION = '0.70';
use base qw( IO::Async::Notifier );
use IO::Async::Timer::Countdown;
use Carp;
=head1 NAME
C<IO::Async::Function> - call a function asynchronously
=head1 SYNOPSIS
use IO::Async::Function;
use IO::Async::Loop;
my $loop = IO::Async::Loop->new;
my $function = IO::Async::Function->new(
code => sub {
my ( $number ) = @_;
return is_prime( $number );
},
);
$loop->add( $function );
$function->call(
args => [ 123454321 ],
)->on_done( sub {
my $isprime = shift;
print "123454321 " . ( $isprime ? "is" : "is not" ) . " a prime number\n";
})->on_fail( sub {
print STDERR "Cannot determine if it's prime - $_[0]\n";
})->get;
=head1 DESCRIPTION
This subclass of L<IO::Async::Notifier> wraps a function body in a collection
of worker processes, to allow it to execute independently of the main process.
The object acts as a proxy to the function, allowing invocations to be made by
passing in arguments, and invoking a continuation in the main process when the
function returns.
The object represents the function code itself, rather than one specific
invocation of it. It can be called multiple times, by the C<call> method.
Multiple outstanding invocations can be called; they will be dispatched in
the order they were queued. If only one worker process is used then results
will be returned in the order they were called. If multiple are used, then
each request will be sent in the order called, but timing differences between
each worker may mean results are returned in a different order.
Since the code block will be called multiple times within the same child
process, it must take care not to modify any of its state that might affect
subsequent calls. Since it executes in a child process, it cannot make any
modifications to the state of the parent program. Therefore, all the data
required to perform its task must be represented in the call arguments, and
all of the result must be represented in the return values.
The Function object is implemented using an L<IO::Async::Routine> with two
L<IO::Async::Channel> objects to pass calls into and results out from it.
The L<IO::Async> framework generally provides mechanisms for multiplexing IO
tasks between different handles, so there aren't many occasions when such an
asynchronous function is necessary. Two cases where this does become useful
are:
=over 4
=item 1.
When a large amount of computationally-intensive work needs to be performed
(for example, the C<is_prime> test in the example in the C<SYNOPSIS>).
=item 2.
When a blocking OS syscall or library-level function needs to be called, and
no nonblocking or asynchronous version is supplied. This is used by
L<IO::Async::Resolver>.
=back
This object is ideal for representing "pure" functions; that is, blocks of
code which have no stateful effect on the process, and whose result depends
only on the arguments passed in. For a more general co-routine ability, see
also L<IO::Async::Routine>.
=cut
=head1 PARAMETERS
The following named parameters may be passed to C<new> or C<configure>:
=head2 code => CODE
The body of the function to execute.
@result = $code->( @args )
=head2 init_code => CODE
Optional. If defined, this is invoked exactly once in every child process or
thread, after it is created, but before the first invocation of the function
body itself.
$init_code->()
=head2 model => "fork" | "thread"
Optional. Requests a specific L<IO::Async::Routine> model. If not supplied,
leaves the default choice up to Routine.
=head2 min_workers => INT
=head2 max_workers => INT
local/lib/perl5/IO/Async/Function.pm view on Meta::CPAN
use IO::Async::Channel;
sub new
{
my $class = shift;
my %params = @_;
my $arg_channel = IO::Async::Channel->new;
my $ret_channel = IO::Async::Channel->new;
my $init = delete $params{init_code};
my $code = delete $params{code};
$params{code} = sub {
$init->() if defined $init;
while( my $args = $arg_channel->recv ) {
my @ret;
my $ok = eval { @ret = $code->( @$args ); 1 };
if( $ok ) {
$ret_channel->send( [ r => @ret ] );
}
elsif( ref $@ ) {
# Presume that $@ is an ARRAYref of error results
$ret_channel->send( [ e => @{ $@ } ] );
}
else {
chomp( my $e = "$@" );
$ret_channel->send( [ e => $e, error => ] );
}
}
};
my $worker = $class->SUPER::new(
%params,
channels_in => [ $arg_channel ],
channels_out => [ $ret_channel ],
);
$worker->{arg_channel} = $arg_channel;
$worker->{ret_channel} = $ret_channel;
return $worker;
}
sub configure
{
my $self = shift;
my %params = @_;
exists $params{$_} and $self->{$_} = delete $params{$_} for qw( exit_on_die max_calls );
$self->SUPER::configure( %params );
}
sub stop
{
my $worker = shift;
$worker->{arg_channel}->close;
if( my $function = $worker->parent ) {
delete $function->{workers}{$worker->id};
if( $worker->{busy} ) {
$worker->{remove_on_idle}++;
}
else {
$function->remove_child( $worker );
}
}
}
sub call
{
my $worker = shift;
my ( $args ) = @_;
$worker->{arg_channel}->send_encoded( $args );
$worker->{busy} = 1;
$worker->{max_calls}--;
return $worker->{ret_channel}->recv->then(
# on recv
$worker->_capture_weakself( sub {
my ( $worker, $result ) = @_;
my ( $type, @values ) = @$result;
$worker->stop if !$worker->{max_calls} or
$worker->{exit_on_die} && $type eq "e";
if( $type eq "r" ) {
return Future->done( @values );
}
elsif( $type eq "e" ) {
return Future->fail( @values );
}
else {
die "Unrecognised type from worker - $type\n";
}
} ),
# on EOF
$worker->_capture_weakself( sub {
my ( $worker ) = @_;
$worker->stop;
return Future->fail( "closed", "closed" );
} )
)->on_ready( $worker->_capture_weakself( sub {
my ( $worker, $f ) = @_;
$worker->{busy} = 0;
my $function = $worker->parent;
$function->_dispatch_pending if $function;
$function->remove_child( $worker ) if $function and $worker->{remove_on_idle};
}));
}
=head1 EXAMPLES
=head2 Extended Error Information on Failure
The array-unpacking form of exception indiciation allows the function body to
more precicely control the resulting failure from the C<call> future.
my $divider = IO::Async::Function->new(
code => sub {
my ( $numerator, $divisor ) = @_;
$divisor == 0 and
die [ "Cannot divide by zero", div_zero => $numerator, $divisor ];
return $numerator / $divisor;
}
);
=head1 NOTES
For the record, 123454321 is 11111 * 11111, a square number, and therefore not
prime.
=head1 AUTHOR
Paul Evans <leonerd@leonerd.org.uk>
=cut
0x55AA;
( run in 0.774 second using v1.01-cache-2.11-cpan-39bf76dae61 )