<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">=pod

=encoding utf8

=head1 NAME

Mojo::IOLoop::HoboProcess - Subprocesses with MCE::Hobo

=head1 VERSION

This document describes Mojo::IOLoop::HoboProcess version 0.005.

=head1 SYNOPSIS

  use feature 'say';
  use Mojo::IOLoop::HoboProcess;

  # Operation that would block the event loop for 5 seconds
  my $subprocess = Mojo::IOLoop::HoboProcess-&gt;new;

  $subprocess-&gt;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
  Mojo::IOLoop-&gt;start unless Mojo::IOLoop-&gt;is_running;

=head1 DESCRIPTION

Like L&lt;Mojo::IOLoop::Subprocess&gt;, spawns subprocesses with MCE::Hobo instead.

L&lt;Mojo::IOLoop::HoboProcess&gt; allows L&lt;Mojo::IOLoop&gt; to perform computationally
expensive operations in subprocesses, without blocking the event loop.

This module is supported on all platforms where L&lt;MCE::Shared&gt; is supported.

=head1 ATTRIBUTES

L&lt;Mojo::IOLoop::HoboProcess&gt; implements the following attribute.

=head2 timeout

  my $timeout = $subprocess-&gt;timeout;
  $subprocess-&gt;timeout(300);

Set to a non-zero value to enable timeout. The default is 0.

=head2 ioloop

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

Event loop object to control, defaults to the global L&lt;Mojo::IOLoop&gt; singleton.

=head1 METHODS

L&lt;Mojo::IOLoop::HoboProcess&gt; inherits all methods from L&lt;Mojo::Base&gt; and
implements the following new ones.

=head2 exit

  sub { $^O eq 'MSWin32' ? shift-&gt;exit(0) : exit(0) }, # not recommended
  sub { shift-&gt;exit(0) }, # do this instead or call MCE::Hobo-&gt;exit(0)

  sub { exit(0) }, # safe on Cygwin and UNIX platforms

Exit a thread (Windows) or process (other platforms).

=head2 pid

  my $pid = $subprocess-&gt;pid;

  $$.$tid  Windows (only), includes thread id
  $$       Cygwin and UNIX platforms

Process id of the spawned subprocess if available.

=head2 run

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

Execute the first callback in a child process and wait for it to return one or
more values, without blocking L&lt;/"ioloop"&gt; 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, is serialized automatically
by L&lt;MCE::Hobo&gt;, using L&lt;Sereal&gt; 3.015+ if installed or L&lt;Storable&gt; otherwise.

=head2 hoboprocess

The C&lt;hoboprocess&gt; method is injected into Mojo::IOLoop.

  use Mojo::IOLoop;
  use Mojo::IOLoop::HoboProcess;

  my $subprocess = Mojo::IOLoop-&gt;hoboprocess( sub {...}, sub {...} );
  my $subprocess = $loop-&gt;hoboprocess( sub {...}, sub {...} );

Build Mojo::IOLoop::HoboProcess object to perform computationally expensive
operations in subprocesses, without blocking the event loop. Callbacks will be
passed along to "run" in Mojo::IOLoop::HoboProcess.

  # Concurrent subprocesses
  my ($fail, $result) = ();

  Mojo::IOLoop-&gt;delay(
    sub {
      my $delay = shift;
      Mojo::IOLoop-&gt;hoboprocess( sub {1}, $delay-&gt;begin );
      Mojo::IOLoop-&gt;hoboprocess( sub {2}, $delay-&gt;begin );
    },
    sub {
      my ( $delay, $err1, $result1, $err2, $result2 ) = @_;
      $fail = $err1 || $err2;
      $result = [ $result1, $result2 ];
    }
  )-&gt;wait;

=head1 EXAMPLES

The following is a variation of the synopsis above for demonstrating data
sharing between subprocesses.

  use Mojo::Cache;
  use Mojo::IOLoop::HoboProcess;

  use MCE::Shared;

  # Construct a shared cache and counter variable
  my $cache   = MCE::Shared-&gt;share( Mojo::Cache-&gt;new( max_keys =&gt; 50 ) );
  my $counter = MCE::Shared-&gt;scalar(0);

  # Also, construct a shared file handle
  mce_open my $OUT, "&gt;", \*STDOUT or die "$!";

  # Operations that would block the event loop for 3+ seconds
  my $subprocess1 = Mojo::IOLoop::HoboProcess-&gt;new;
  my $subprocess2 = Mojo::IOLoop::HoboProcess-&gt;new;

  $subprocess1-&gt;run(
    sub {
      my $subprocess = shift;
      say $OUT "Subprocess [$$] started";
      $cache-&gt;set('key1', 'foo');
      sleep 4;
      my $val = $cache-&gt;get('key2');
      return "â™¥", "Mojolicious lots: $val: " . $counter-&gt;incr;
    },
    sub {
      my ($subprocess, $err, @results) = @_;
      say $OUT "Subprocess error: $err" and return if $err;
      say $OUT "I $results[0] $results[1]!";
    }
  );

  $subprocess2-&gt;run(
    sub {
      my $subprocess = shift;
      say $OUT "Subprocess [$$] started";
      $cache-&gt;set('key2', 'baz');
      sleep 3;
      my $val = $cache-&gt;get('key1');
      return "â™¥", "Mojolicious more: $val: " . $counter-&gt;incr;
    },
    sub {
      my ($subprocess, $err, @results) = @_;
      say $OUT "Subprocess error: $err" and return if $err;
      say $OUT "I $results[0] $results[1]!";
    }
  );

  # Start event loop if necessary
  Mojo::IOLoop-&gt;start unless Mojo::IOLoop-&gt;is_running;

  __END__
  Program output.

  Subprocess [7625] started
  Subprocess [7626] started
  I â™¥ Mojolicious more: foo: 1!
  I â™¥ Mojolicious lots: baz: 2!

A parallel demonstration for Recurring Monte Carlo Pi Calculation.

  # Original source by Demian Riccardi and Joel Berger.
  # https://gist.github.com/dmr3/e69127ab449bdabd5af7b000c9b5b3b1
  #
  # Parallel demonstration by Mario Roy.

  use Mojolicious::Lite;

  use MCE::Hobo;
  use MCE::Shared;

  any '/' =&gt; 'index';

  websocket '/data' =&gt; sub {
    my $self = shift;
    my ($pi,$runs,$new_runs) = (0,0,1000000);

    my $timer = Mojo::IOLoop-&gt;recurring( 0.1 =&gt; sub {
      ($pi,$runs) = calc_pi($pi,$runs,$new_runs);
      $self-&gt;send({ json =&gt; [$runs,$pi] });
    });

    $self-&gt;on( finish =&gt; sub {
      Mojo::IOLoop-&gt;remove($timer);
    });
  };

  sub gen_data {
    my $x = shift;
    return [ $x, sin( $x + 2*rand() - 2*rand() ) ]
  }

  sub calc_pi {
    my ( $pi, $total_runs, $new_runs ) = @_;

    # use the itr to show how to submit multiples
    my $cnt_pi = MCE::Shared-&gt;scalar(
      -1 * ( ( $pi * $total_runs ) / 4 - $total_runs )
    );

    # shared sequence-generator
    my $seq = MCE::Shared-&gt;sequence(
      { chunk_size =&gt; 10000, bounds_only =&gt; 1 },
      1, $new_runs
    );

    # Run
    my $routine = sub {
      while ( my ($beg, $end) = $seq-&gt;next ) {
        my ($cnt, $x, $y) = (0);

        foreach ( $beg .. $end ) {
          $x = rand(1);
          $y = rand(1);
          $cnt++ if $x * $x + $y * $y &gt; 1;
        }

        $cnt_pi-&gt;incrby($cnt);
      }
    };

    MCE::Hobo-&gt;create( $routine ) for ( 1 .. 3 );
    MCE::Hobo-&gt;waitall;

    $total_runs += $new_runs;

    $pi = 4 * ( $total_runs - $cnt_pi-&gt;get ) / $total_runs;

    return ($pi, $total_runs);
  }

  app-&gt;start;

  __DATA__

  @@ index.html.ep
  &lt;!DOCTYPE html&gt;
  &lt;html&gt;
    &lt;head&gt;
      &lt;title&gt;&lt;%= title %&gt;&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
      %= content
    &lt;/body&gt;
  &lt;html&gt;

  %= javascript 'https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'
  %= javascript 'https://cdnjs.cloudflare.com/ajax/libs/flot/0.8.3/jquery.flot.js'

  &lt;div id="plot" style="width:600px;height:300px"&gt;
  &lt;/div&gt;

  %= javascript begin
    var data = [];
    var plot = $.plot($('#plot'), [ data ]);

    var url = '&lt;%= url_for('data')-&gt;to_abs %&gt;';
    var ws = new WebSocket( url );

    ws.onmessage = function(e){
      var point = JSON.parse(e.data);
      data.push(point);
      plot.setData([data]);
      plot.setupGrid();
      plot.draw();
    };
  % end

=head1 ACKNOWLEDGMENTS

L&lt;Mojo::IOLoop::Subprocess&gt; and L&lt;Mojo::IOLoop::Subprocess::Sereal&gt;
were used as templates in the making of this module.

=head1 AUTHOR

Mario E. Roy, S&lt;E&lt;lt&gt;marioeroy AT gmail DOT comE&lt;gt&gt;&gt;

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2016-2017 by Mario E. Roy

Mojo::IOLoop::HoboProcess is released under the same license as Perl.

See L&lt;http://dev.perl.org/licenses/&gt; for more information.

=head1 SEE ALSO

L&lt;Mojolicious&gt;, L&lt;Mojolicious::Guides&gt;, L&lt;http://mojolicious.org&gt;

L&lt;MCE::Shared&gt;

=cut
</pre></body></html>