NAME

Mojo::IOLoop::Subprocess - Subprocesses

SYNOPSIS

use Mojo::IOLoop::Subprocess;

# Operation that would block the event loop for 5 seconds
my $subprocess = Mojo::IOLoop::Subprocess->new;
$subprocess->run(
  sub {
    my $subprocess = shift;
    sleep 5;
    return '♥', 'Mojolicious';
  },
  sub {
    my ($subprocess, $err, @results) = @_;
    say "Subprocess error: $err" and return if $err;
    say "I $results[0] $results[1]!";
  }
);

# Start event loop if necessary
$subprocess->ioloop->start unless $subprocess->ioloop->is_running;

DESCRIPTION

Mojo::IOLoop::Subprocess allows Mojo::IOLoop to perform computationally expensive operations in subprocesses, without blocking the event loop.

ATTRIBUTES

Mojo::IOLoop::Subprocess implements the following attributes.

deserialize

my $cb      = $subprocess->deserialize;
$subprocess = $subprocess->deserialize(sub {...});

A callback used to deserialize subprocess return values, defaults to using Storable.

$subprocess->deserialize(sub {
  my $bytes = shift;
  return [];
});

ioloop

my $loop    = $subprocess->ioloop;
$subprocess = $subprocess->ioloop(Mojo::IOLoop->new);

Event loop object to control, defaults to the global Mojo::IOLoop singleton.

serialize

my $cb      = $subprocess->serialize;
$subprocess = $subprocess->serialize(sub {...});

A callback used to serialize subprocess return values, defaults to using Storable.

$subprocess->serialize(sub {
  my $array = shift;
  return '';
});

METHODS

Mojo::IOLoop::Subprocess inherits all methods from Mojo::Base and implements the following new ones.

pid

my $pid = $subprocess->pid;

Process id of the spawned subprocess if available.

run

$subprocess = $subprocess->run(sub {...}, sub {...});

Execute the first callback in a child process and wait for it to return one or more values, without blocking "ioloop" in the parent process. Then execute the second callback in the parent process with the results. The return values of the first callback and exceptions thrown by it, will be serialized with Storable, so they can be shared between processes.

SEE ALSO

Mojolicious, Mojolicious::Guides, https://mojolicious.org.