.\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.43) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "MCE::Examples 3pm" .TH MCE::Examples 3pm "2023-09-29" "perl v5.36.0" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" MCE::Examples \- Various examples and demonstrations .SH "VERSION" .IX Header "VERSION" This document describes MCE::Examples version 1.889 .SH "INCLUDED WITH THE DISTRIBUTION" .IX Header "INCLUDED WITH THE DISTRIBUTION" A wrapper script for parallelizing the grep binary. Hence, processing is done by the binary, not Perl. This wrapper resides under the bin directory. .PP .Vb 3 \& mce_grep \& A wrapper script with support for the following C binaries. \& agrep, grep, egrep, fgrep, and tre\-agrep \& \& Chunking may be applied either at the [file] level, for large \& file(s), or at the [list] level when parsing many files \& recursively. \& \& The gain in performance is noticeable for expensive patterns, \& especially with agrep and tre\-agrep. .Ve .SH "MCE EXAMPLES ON GITHUB" .IX Header "MCE EXAMPLES ON GITHUB" The examples directory, beginning with 1.700, is maintained separately at a GitHub repository and no longer included with the Perl \s-1MCE\s0 distribution. .SH "PROCESSING INPUT DATA" .IX Header "PROCESSING INPUT DATA" The next section describes ways to process input data in \s-1MCE.\s0 .SS "\s-1CHUNK_SIZE\s0 => 1 (in essence, disabling chunking)" .IX Subsection "CHUNK_SIZE => 1 (in essence, disabling chunking)" Imagine a long running process and wanting to parallelize an array against a pool of workers. The sequence option may be used if simply wanting to loop through a sequence of numbers instead. .PP Below, a callback function is used for displaying results. The logic shows how one can output results immediately while still preserving output order as if processing serially. The \f(CW%tmp\fR hash is a temporary cache for out-of-order results. .PP .Vb 1 \& use MCE; \& \& ## Return an iterator for preserving output order. \& \& sub preserve_order { \& my (%result_n, %result_d); my $order_id = 1; \& \& return sub { \& my ($chunk_id, $n, $data) = @_; \& \& $result_n{ $chunk_id } = $n; \& $result_d{ $chunk_id } = $data; \& \& while (1) { \& last unless exists $result_d{$order_id}; \& \& printf "n: %5d sqrt(n): %7.3f\en", \& $result_n{$order_id}, $result_d{$order_id}; \& \& delete $result_n{$order_id}; \& delete $result_d{$order_id}; \& \& $order_id++; \& } \& \& return; \& }; \& } \& \& ## Use $chunk_ref\->[0] or $_ to retrieve the element. \& my @input_data = (0 .. 18000 \- 1); \& \& my $mce = MCE\->new( \& gather => preserve_order, input_data => \e@input_data, \& chunk_size => 1, max_workers => 3, \& \& user_func => sub { \& my ($mce, $chunk_ref, $chunk_id) = @_; \& MCE\->gather($chunk_id, $_, sqrt($_)); \& } \& ); \& \& $mce\->run; .Ve .PP This does the same thing using the foreach \*(L"sugar\*(R" method. .PP .Vb 1 \& use MCE; \& \& sub preserve_order { \& ... \& } \& \& my $mce = MCE\->new( \& chunk_size => 1, max_workers => 3, \& gather => preserve_order \& ); \& \& ## Use $chunk_ref\->[0] or $_ to retrieve the element. \& my @input_data = (0 .. 18000 \- 1); \& \& $mce\->foreach( \e@input_data, sub { \& my ($mce, $chunk_ref, $chunk_id) = @_; \& MCE\->gather($chunk_id, $_, sqrt($_)); \& }); .Ve .PP The 2 examples described above were done using the Core \s-1API. MCE 1.5\s0 comes with several models. The MCE::Loop model is used below. .PP .Vb 1 \& use MCE::Loop; \& \& sub preserve_order { \& ... \& } \& \& MCE::Loop\->init( \& chunk_size => 1, max_workers => 3, \& gather => preserve_order \& ); \& \& ## Use $chunk_ref\->[0] or $_ to retrieve the element. \& my @input_data = (0 .. 18000 \- 1); \& \& mce_loop { \& my ($mce, $chunk_ref, $chunk_id) = @_; \& MCE\->gather($chunk_id, $_, sqrt($_)); \& \& } @input_data; \& \& MCE::Loop\->finish; .Ve .SS "\s-1CHUNKING INPUT DATA\s0" .IX Subsection "CHUNKING INPUT DATA" Chunking has the effect of reducing \s-1IPC\s0 overhead by many folds. A chunk containing \f(CW$chunk_size\fR items is sent to the next available worker. .PP .Vb 1 \& use MCE; \& \& ## Return an iterator for preserving output order. \& \& sub preserve_order { \& my (%result_n, %result_d, $size); my $order_id = 1; \& \& return sub { \& my ($chunk_id, $n_ref, $data_ref) = @_; \& \& $result_n{ $chunk_id } = $n_ref; \& $result_d{ $chunk_id } = $data_ref; \& \& while (1) { \& last unless exists $result_d{$order_id}; \& $size = @{ $result_d{$order_id} }; \& \& for (0 .. $size \- 1) { \& printf "n: %5d sqrt(n): %7.3f\en", \& $result_n{$order_id}\->[$_], $result_d{$order_id}\->[$_]; \& } \& \& delete $result_n{$order_id}; \& delete $result_d{$order_id}; \& \& $order_id++; \& } \& \& return; \& }; \& } \& \& ## Chunking requires one to loop inside the code block. \& my @input_data = (0 .. 18000 \- 1); \& \& my $mce = MCE\->new( \& gather => preserve_order, input_data => \e@input_data, \& chunk_size => 500, max_workers => 3, \& \& user_func => sub { \& my ($mce, $chunk_ref, $chunk_id) = @_; \& my (@n, @result); \& \& foreach ( @{ $chunk_ref } ) { \& push @n, $_; \& push @result, sqrt($_); \& } \& \& MCE\->gather($chunk_id, \e@n, \e@result); \& } \& ); \& \& $mce\->run; .Ve .PP This does the same thing using the forchunk \*(L"sugar\*(R" method. .PP .Vb 1 \& use MCE; \& \& sub preserve_order { \& ... \& } \& \& my $mce = MCE\->new( \& chunk_size => 500, max_workers => 3, \& gather => preserve_order \& ); \& \& ## Chunking requires one to loop inside the code block. \& my @input_data = (0 .. 18000 \- 1); \& \& $mce\->forchunk( \e@input_data, sub { \& my ($mce, $chunk_ref, $chunk_id) = @_; \& my (@n, @result); \& \& foreach ( @{ $chunk_ref } ) { \& push @n, $_; \& push @result, sqrt($_); \& } \& \& MCE\->gather($chunk_id, \e@n, \e@result); \& }); .Ve .PP Finally, chunking with the MCE::Loop model. .PP .Vb 1 \& use MCE::Loop; \& \& sub preserve_order { \& ... \& } \& \& MCE::Loop\->init( \& chunk_size => 500, max_workers => 3, \& gather => preserve_order \& ); \& \& ## Chunking requires one to loop inside the code block. \& my @input_data = (0 .. 18000 \- 1); \& \& mce_loop { \& my ($mce, $chunk_ref, $chunk_id) = @_; \& my (@n, @result); \& \& foreach ( @{ $chunk_ref } ) { \& push @n, $_; \& push @result, sqrt($_); \& } \& \& MCE\->gather($chunk_id, \e@n, \e@result); \& \& } @input_data; \& \& MCE::Loop\->finish; .Ve .SH "DEMO APPLYING SEQUENCES WITH USER_TASKS" .IX Header "DEMO APPLYING SEQUENCES WITH USER_TASKS" The following is an extract from the seq_demo.pl example included with \s-1MCE.\s0 Think of having several MCEs running in parallel. The sequence and chunk_size options may be specified uniquely per each task. .PP The input scalar \f(CW$_\fR (not shown below) contains the same value as \f(CW$seq_n\fR in user_func. .PP .Vb 2 \& use MCE; \& use Time::HiRes \*(Aqsleep\*(Aq; \& \& ## Run with seq_demo.pl | sort \& \& sub user_func { \& my ($mce, $seq_n, $chunk_id) = @_; \& \& my $wid = MCE\->wid; \& my $task_id = MCE\->task_id; \& my $task_wid = MCE\->task_wid; \& \& if (ref $seq_n eq \*(AqARRAY\*(Aq) { \& ## seq_n or $_ is an array reference when chunk_size > 1 \& foreach (@{ $seq_n }) { \& MCE\->printf( \& "task_id %d: seq_n %s: chunk_id %d: wid %d: task_wid %d\en", \& $task_id, $_, $chunk_id, $wid, $task_wid \& ); \& } \& } \& else { \& MCE\->printf( \& "task_id %d: seq_n %s: chunk_id %d: wid %d: task_wid %d\en", \& $task_id, $seq_n, $chunk_id, $wid, $task_wid \& ); \& } \& \& sleep 0.003; \& \& return; \& } \& \& ## Each task can be configured uniquely. \& \& my $mce = MCE\->new( \& user_tasks => [{ \& max_workers => 2, \& chunk_size => 1, \& sequence => { begin => 11, end => 19, step => 1 }, \& user_func => \e&user_func \& },{ \& max_workers => 2, \& chunk_size => 5, \& sequence => { begin => 21, end => 29, step => 1 }, \& user_func => \e&user_func \& },{ \& max_workers => 2, \& chunk_size => 3, \& sequence => { begin => 31, end => 39, step => 1 }, \& user_func => \e&user_func \& }] \& ); \& \& $mce\->run; \& \& \-\- Output \& \& task_id 0: seq_n 11: chunk_id 1: wid 2: task_wid 2 \& task_id 0: seq_n 12: chunk_id 2: wid 1: task_wid 1 \& task_id 0: seq_n 13: chunk_id 3: wid 2: task_wid 2 \& task_id 0: seq_n 14: chunk_id 4: wid 1: task_wid 1 \& task_id 0: seq_n 15: chunk_id 5: wid 2: task_wid 2 \& task_id 0: seq_n 16: chunk_id 6: wid 1: task_wid 1 \& task_id 0: seq_n 17: chunk_id 7: wid 2: task_wid 2 \& task_id 0: seq_n 18: chunk_id 8: wid 1: task_wid 1 \& task_id 0: seq_n 19: chunk_id 9: wid 2: task_wid 2 \& task_id 1: seq_n 21: chunk_id 1: wid 3: task_wid 1 \& task_id 1: seq_n 22: chunk_id 1: wid 3: task_wid 1 \& task_id 1: seq_n 23: chunk_id 1: wid 3: task_wid 1 \& task_id 1: seq_n 24: chunk_id 1: wid 3: task_wid 1 \& task_id 1: seq_n 25: chunk_id 1: wid 3: task_wid 1 \& task_id 1: seq_n 26: chunk_id 2: wid 4: task_wid 2 \& task_id 1: seq_n 27: chunk_id 2: wid 4: task_wid 2 \& task_id 1: seq_n 28: chunk_id 2: wid 4: task_wid 2 \& task_id 1: seq_n 29: chunk_id 2: wid 4: task_wid 2 \& task_id 2: seq_n 31: chunk_id 1: wid 5: task_wid 1 \& task_id 2: seq_n 32: chunk_id 1: wid 5: task_wid 1 \& task_id 2: seq_n 33: chunk_id 1: wid 5: task_wid 1 \& task_id 2: seq_n 34: chunk_id 2: wid 6: task_wid 2 \& task_id 2: seq_n 35: chunk_id 2: wid 6: task_wid 2 \& task_id 2: seq_n 36: chunk_id 2: wid 6: task_wid 2 \& task_id 2: seq_n 37: chunk_id 3: wid 5: task_wid 1 \& task_id 2: seq_n 38: chunk_id 3: wid 5: task_wid 1 \& task_id 2: seq_n 39: chunk_id 3: wid 5: task_wid 1 .Ve .SH "GLOBALLY SCOPED VARIABLES AND MCE MODELS" .IX Header "GLOBALLY SCOPED VARIABLES AND MCE MODELS" It is possible that Perl may create a new code ref on subsequent runs causing \&\s-1MCE\s0 models to re-spawn. One solution to this is to declare global variables, referenced by workers, with \*(L"our\*(R" instead of \*(L"my\*(R". .PP Let's take a look. The \f(CW$i\fR variable is declared with my and being reference in both user_begin and mce_loop blocks. This will cause Perl to create a new code ref for mce_loop on subsequent runs. .PP .Vb 1 \& use MCE::Loop; \& \& my $i = 0; ## <\-\- this is the reason, try our instead \& \& MCE::Loop\->init( \& user_begin => sub { \& print "process_id: $$\en" if MCE\->wid == 1; \& $i++; \& }, \& chunk_size => 1, max_workers => \*(Aqauto\*(Aq, \& ); \& \& for (1..2) { \& ## Perl creates another code block ref causing workers \& ## to re\-spawn on subsequent runs. \& print "\en"; mce_loop { print "$i: $_\en" } 1..4; \& } \& \& MCE::Loop\->finish; \& \& \-\- Output \& \& process_id: 51380 \& 1: 1 \& 1: 2 \& 1: 3 \& 1: 4 \& \& process_id: 51388 \& 1: 1 \& 1: 2 \& 1: 3 \& 1: 4 .Ve .PP By making the one line change, we see that workers persist for the duration of the script. .PP .Vb 1 \& use MCE::Loop; \& \& our $i = 0; ## <\-\- changed my to our \& \& MCE::Loop\->init( \& user_begin => sub { \& print "process_id: $$\en" if MCE\->wid == 1; \& $i++; \& }, \& chunk_size => 1, max_workers => \*(Aqauto\*(Aq, \& ); \& \& for (1..2) { \& ## Workers persist between runs. No re\-spawning. \& print "\en"; mce_loop { print "$i: $_\en" } 1..4; \& } \& \& \-\- Output \& \& process_id: 51457 \& 1: 1 \& 1: 2 \& 1: 4 \& 1: 3 \& \& process_id: 51457 \& 2: 1 \& 2: 2 \& 2: 3 \& 2: 4 .Ve .PP One may alternatively specify a code reference to existing routines for user_begin and mce_loop. Take notice of the comma after \e&_func though. .PP .Vb 1 \& use MCE::Loop; \& \& my $i = 0; ## my (ok) \& \& sub _begin { \& print "process_id: $$\en" if MCE\->wid == 1; \& $i++; \& } \& sub _func { \& print "$i: $_\en"; \& } \& \& MCE::Loop\->init( \& user_begin => \e&_begin, \& chunk_size => 1, max_workers => \*(Aqauto\*(Aq, \& ); \& \& for (1..2) { \& print "\en"; mce_loop \e&_func, 1..4; \& } \& \& MCE::Loop\->finish; \& \& \-\- Output \& \& process_id: 51626 \& 1: 1 \& 1: 2 \& 1: 3 \& 1: 4 \& \& process_id: 51626 \& 2: 1 \& 2: 2 \& 2: 3 \& 2: 4 .Ve .SH "MANDELBROT DEMONSTRATION" .IX Header "MANDELBROT DEMONSTRATION" For the next demonstration, MCE::Relay allows a section of code to run serially and orderly between workers. Relay capabilities is enabled with the \f(CW\*(C`init_relay\*(C'\fR option, which loads MCE::Relay. .PP .Vb 2 \& # perl mandelbrot.pl 16000 > image.pbm \& # outputs a pbm binary to STDOUT \& \& # The Computer Language Benchmarks Game \& # https://benchmarksgame\-team.pages.debian.net/benchmarksgame/ \& # \& # Started with: \& # C# : Adapted by Antti Lankila from Isaac Gouy\*(Aqs implementation \& # Perl: Contributed by Mykola Zubach \& # \& # MCE::Loop version by Mario Roy \& # requires MCE 1.807+ \& \& use strict; \& use warnings; \& \& use MCE::Loop; \& \& use constant MAXITER => 50; \& use constant LIMIT => 4.0; \& use constant XMIN => \-1.5; \& use constant YMIN => \-1.0; \& \& my ( $w, $h, $m, $invN ); \& \& sub draw_lines { \& my ( $y1, $y2 ) = @_; \& my @result; \& \& # Workers run simultaneously, in parallel. \& \& for my $y ( $y1 .. $y2 ) { \& my ( $bits, $xcounter, @line ) = ( 0, 0 ); \& my $Ci = $y * $invN + YMIN; \& \& for my $x ( 0 .. $w \- 1 ) { \& my ( $Zr, $Zi, $Tr, $Ti ) = ( 0, 0, 0, 0 ); \& my $Cr = $x * $invN + XMIN; \& \& $bits = $bits << 1; \& \& for ( 1 .. MAXITER ) { \& $Zi = $Zi * 2 * $Zr + $Ci; \& $Zr = $Tr \- $Ti + $Cr; \& $Ti = $Zi * $Zi, $Tr = $Zr * $Zr; \& \& $bits |= 1, last if ( $Tr + $Ti > LIMIT ); \& } \& \& if ( ++$xcounter == 8 ) { \& push @line, $bits ^ 0xff; \& $bits = $xcounter = 0; \& } \& } \& \& if ( $xcounter ) { \& push @line, ( $bits << ( 8 \- $xcounter ) ) ^ 0xff; \& } \& \& push @result, pack \*(AqC*\*(Aq, @line; \& } \& \& # Statements between lock & unlock are processed serially & orderly. \& \& MCE\->relay_lock; \& \& print @result; # Workers display upper\-half only. \& MCE\->gather( @result ); # Gather lines for the manager\-process. \& \& MCE\->relay_unlock; \& } \& \& ## MAIN() \& \& # Important, must flush output immediately. \& \& $| = 1; binmode STDOUT; \& \& $w = $h = shift || 200; \& $m = int( $h / 2 ); \& $invN = 2 / $w; \& \& print "P4\en$w $h\en"; # PBM image header. \& \& # Workers display upper\-half only. Also, lines are gathered to be \& # displayed later by the manager\-process after running. \& \& MCE::Loop\->init( \& init_relay => 0, # Enables MCE::Relay capabilities if defined. \& max_workers => 4, \& bounds_only => 1, \& ); \& \& my @upper = mce_loop_s { draw_lines( $_[1][0], $_[1][1] ) } 0, $m; \& \& MCE::Loop\->finish; \& \& # Remove first and last lines from the upper half. \& # Then, output bottom half. \& \& shift @upper, pop @upper; \& print reverse @upper; .Ve .SH "MONTE CARLO SIMULATION" .IX Header "MONTE CARLO SIMULATION" There is an article on the web (search for comp.lang.perl.misc \s-1MCE\s0) suggesting that MCE::Examples does not cover a simple simulation scenario. This section demonstrates just that. .PP The serial code is based off the one by \*(L"gamo\*(R". A sleep is added to imitate extra \s-1CPU\s0 time. The while loop is wrapped within a for loop to run 10 times. The random number generator is seeded as well. .PP .Vb 1 \& use Time::HiRes qw/sleep time/; \& \& srand 5906; \& \& my ($var, $foo, $bar) = (1, 2, 3); \& my ($r, $a, $b); \& \& my $start = time; \& \& for (1..10) { \& while (1) { \& $r = rand; \& \& $a = $r * ($var + $foo + $bar); \& $b = sqrt($var + $foo + $bar); \& \& last if ($a < $b + 0.001 && $a > $b \- 0.001); \& sleep 0.002; \& } \& \& print "$r \-> $a\en"; \& } \& \& my $end = time; \& \& printf {*STDERR} "\en## compute time: %0.03f secs\en\en", $end \- $start; \& \& \-\- Output \& \& 0.408246276657106 \-> 2.44947765994264 \& 0.408099657137821 \-> 2.44859794282693 \& 0.408285842931324 \-> 2.44971505758794 \& 0.408342292008765 \-> 2.45005375205259 \& 0.408333076522673 \-> 2.44999845913604 \& 0.408344266898869 \-> 2.45006560139321 \& 0.408084104120526 \-> 2.44850462472316 \& 0.408197400014714 \-> 2.44918440008828 \& 0.408344783704855 \-> 2.45006870222913 \& 0.408248062985479 \-> 2.44948837791287 \& \& ## compute time: 93.049 secs .Ve .PP Next, we'd do the same with \s-1MCE.\s0 The demonstration requires at least \s-1MCE 1.509\s0 to run properly. Folks on prior releases (1.505 \- 1.508) will not see output for the 2nd run and beyond. .PP .Vb 2 \& use Time::HiRes qw/sleep time/; \& use MCE::Loop; \& \& srand 5906; \& \& ## Configure MCE. Move common variables inside the user_begin \& ## block when not needed by the manager process. \& \& MCE::Loop\->init( \& user_begin => sub { \& use vars qw($var $foo $bar); \& our ($var, $foo, $bar) = (1, 2, 3); \& }, \& chunk_size => 1, max_workers => \*(Aqauto\*(Aq, \& input_data => \e&_input, gather => \e&_gather \& ); \& \& ## Callback functions. \& \& my ($done, $r, $a); \& \& sub _input { \& return if $done; \& return rand; \& } \& \& sub _gather { \& my ($_r, $_a, $_b) = @_; \& return if $done; \& \& if ($_a < $_b + 0.001 && $_a > $_b \- 0.001) { \& ($done, $r, $a) = (1, $_r, $_a); \& } \& return; \& } \& \& ## Compute in parallel. \& \& my $start = time; \& \& for (1..10) { \& $done = 0; ## Reset $done before running \& \& mce_loop { \& # my ($mce, $chunk_ref, $chunk_id) = @_; \& # my $r = $chunk_ref\->[0]; \& \& my $r = $_; ## Valid due to chunk_size => 1 \& \& my $a = $r * ($var + $foo + $bar); \& my $b = sqrt($var + $foo + $bar); \& \& MCE\->gather($r, $a, $b); \& sleep 0.002; \& }; \& \& print "$r \-> $a\en"; \& } \& \& printf "\en## compute time: %0.03f secs\en\en", time \- $start; \& \& \-\- Output \& \& 0.408246276657106 \-> 2.44947765994264 \& 0.408099657137821 \-> 2.44859794282693 \& 0.408285842931324 \-> 2.44971505758794 \& 0.408342292008765 \-> 2.45005375205259 \& 0.408333076522673 \-> 2.44999845913604 \& 0.408344266898869 \-> 2.45006560139321 \& 0.408084104120526 \-> 2.44850462472316 \& 0.408197400014714 \-> 2.44918440008828 \& 0.408344783704855 \-> 2.45006870222913 \& 0.408248062985479 \-> 2.44948837791287 \& \& ## compute time: 12.990 secs .Ve .PP Well, there you have it. \s-1MCE\s0 is able to complete the same simulation many times faster. .SH "MANY WORKERS RUNNING IN PARALLEL" .IX Header "MANY WORKERS RUNNING IN PARALLEL" There are occasions when one wants several workers to run in parallel without having to specify input_data or sequence. These two options are optional in \&\s-1MCE.\s0 The \*(L"do\*(R" and \*(L"sendto\*(R" methods, for sending data to the manager process, are demonstrated below. Both process serially by the manager process on a first come, first serve basis. .PP .Vb 1 \& use MCE::Flow max_workers => 4; \& \& sub report_stats { \& my ($wid, $msg, $h_ref) = @_; \& print "Worker $wid says $msg: ", $h_ref\->{"counter"}, "\en"; \& } \& \& mce_flow sub { \& my ($mce) = @_; \& my $wid = MCE\->wid; \& \& if ($wid == 1) { \& my %h = ("counter" => 0); \& while (1) { \& $h{"counter"} += 1; \& MCE\->do("report_stats", $wid, "Hey there", \e%h); \& last if ($h{"counter"} == 4); \& sleep 2; \& } \& } \& else { \& my %h = ("counter" => 0); \& while (1) { \& $h{"counter"} += 1; \& MCE\->do("report_stats", $wid, "Welcome..", \e%h); \& last if ($h{"counter"} == 2); \& sleep 4; \& } \& } \& \& MCE\->print(\e*STDERR, "Worker $wid is exiting\en"); \& }; \& \& \-\- Output \& \& Note how worker 2 comes first in the 2nd run below. \& \& $ ./demo.pl \& Worker 1 says Hey there: 1 \& Worker 2 says Welcome..: 1 \& Worker 3 says Welcome..: 1 \& Worker 4 says Welcome..: 1 \& Worker 1 says Hey there: 2 \& Worker 2 says Welcome..: 2 \& Worker 3 says Welcome..: 2 \& Worker 1 says Hey there: 3 \& Worker 2 is exiting \& Worker 3 is exiting \& Worker 4 says Welcome..: 2 \& Worker 4 is exiting \& Worker 1 says Hey there: 4 \& Worker 1 is exiting \& \& $ ./demo.pl \& Worker 2 says Welcome..: 1 \& Worker 1 says Hey there: 1 \& Worker 4 says Welcome..: 1 \& Worker 3 says Welcome..: 1 \& Worker 1 says Hey there: 2 \& Worker 2 says Welcome..: 2 \& Worker 4 says Welcome..: 2 \& Worker 3 says Welcome..: 2 \& Worker 2 is exiting \& Worker 4 is exiting \& Worker 1 says Hey there: 3 \& Worker 3 is exiting \& Worker 1 says Hey there: 4 \& Worker 1 is exiting .Ve .SH "TESTING AND CAPTURING OUTPUT" .IX Header "TESTING AND CAPTURING OUTPUT" Capturing \f(CW\*(C`STDERR\*(C'\fR and \f(CW\*(C`STDOUT\*(C'\fR is possible with App::Cmd::Tester. \&\s-1MCE\s0 v1.708 or later is required to run the demonstration. .PP .Vb 2 \& use App::Cmd::Tester; \& use MCE; \& \& my $mce = MCE\->new( \& max_workers => 4, \& \& user_func => sub { \& my $wid = MCE\->wid; \& \& # MCE\->sendto(\*(Aqstderr\*(Aq, "$wid: sendto err\en"); \& # MCE\->sendto(\e*STDERR, "$wid: sendto err\en"); \& MCE\->print(\e*STDERR, "$wid: print err\en"); \& \& # MCE\->sendto(\*(Aqstdout\*(Aq, "$wid: sendto out\en"); \& # MCE\->sendto(\e*STDOUT, "$wid: sendto out\en"); \& # MCE\->print(\e*STDOUT, "$wid: print out\en"); \& MCE\->print("$wid: print out\en"); \& } \& ); \& \& my $result = test_app( \& $mce => [] \& ); \& \& print "# stderr\en"; \& print $result\->stderr; \& print "\en"; \& \& print "# stdout\en"; \& print $result\->stdout; \& print "\en"; \& \& print "# output\en"; \& print $result\->output; \& print "\en"; \& \& print "# exit code\en"; \& print $result\->exit_code; \& print "\en\en"; \& \& \-\- Output \& \& # stderr \& 3: print err \& 4: print err \& 1: print err \& 2: print err \& \& # stdout \& 3: print out \& 4: print out \& 1: print out \& 2: print out \& \& # output \& 3: print err \& 3: print out \& 4: print err \& 1: print err \& 4: print out \& 1: print out \& 2: print err \& 2: print out \& \& # exit code \& 0 .Ve .PP The next demonstration captures a sequence of numbers orderly. The slot name for \f(CW\*(C`IO::TieCombine\*(C'\fR must be \f(CW\*(C`stdout\*(C'\fR or \f(CW\*(C`stderr\*(C'\fR for \s-1MCE\-\s0>print to work. .PP .Vb 3 \& use MCE::Flow; \& use MCE::Candy; \& use IO::TieCombine; \& \& my $hub = IO::TieCombine\->new; \& \& { \& tie local *STDOUT, $hub, \*(Aqstdout\*(Aq; \& \& MCE::Flow\->init( \& max_workers => 4, \& chunk_size => 500, \& bounds_only => 1, \& gather => MCE::Candy::out_iter_fh(\e*STDOUT), \& ); \& \& mce_flow_s sub { \& my ($mce, $seq, $chunk_id) = @_; \& my $output = \*(Aq\*(Aq; \& \& for my $n ( $seq\->[0] .. $seq\->[1] ) { \& $output .= "$n\en"; \& } \& \& # do this if output order is not required \& # $mce\->print(\e*STDOUT, $output); \& \& # or this if preserving output order is desired \& $mce\->gather($chunk_id, $output); \& \& }, 1, 100000; \& \& MCE::Flow\->finish; \& } \& \& my $content = $hub\->slot_contents(\*(Aqstdout\*(Aq); \& my $answer = join("", map { "$_\en" } 1..100000); \& \& if ($content eq $answer) { \& print "ordered: yes\en"; \& } else { \& print "ordered: no\en"; \& } \& \& \-\- Output \& \& ordered: yes .Ve .SH "CROSS-PLATFORM TEMPLATE FOR BINARY EXECUTABLE" .IX Header "CROSS-PLATFORM TEMPLATE FOR BINARY EXECUTABLE" Making an executable is possible with the PAR::Packer module. On the Windows platform, threads, threads::shared, and exiting via threads are necessary for the binary to exit successfully. .PP .Vb 5 \& # https://metacpan.org/pod/PAR::Packer \& # https://metacpan.org/pod/pp \& # \& # pp \-o demo.exe demo.pl \& # ./demo.exe \& \& use strict; \& use warnings; \& \& use if $^O eq "MSWin32", "threads"; \& use if $^O eq "MSWin32", "threads::shared"; \& \& use Time::HiRes (); # include minimum dependencies for MCE \& use Storable (); \& \& use IO::FDPass (); # optional: for MCE::Shared\->condvar, handle, queue \& use Sereal (); # optional: faster serialization, may omit Storable \& \& use MCE; \& \& my $mce = MCE\->new( \& max_workers => 4, \& user_func => sub { \& print "hello from ", MCE\->wid(), "\en"; \& } \& ); \& \& $mce\->run(); \& \& threads\->exit(0) if $INC{"threads.pm"}; .Ve .PP With MCE::Shared 1.808 and later releases, MCE::Hobo works just the same. The following compiles fine on \s-1UNIX\s0 and the Windows platform. .PP .Vb 5 \& # https://metacpan.org/pod/PAR::Packer \& # https://metacpan.org/pod/pp \& # \& # pp \-o demo.exe demo.pl \& # ./demo.exe \& \& use strict; \& use warnings; \& \& use if $^O eq "MSWin32", "threads"; \& use if $^O eq "MSWin32", "threads::shared"; \& \& use Time::HiRes (); # include minimum dependencies for MCE::Hobo \& use Storable (); \& \& use IO::FDPass (); # optional: for MCE::Shared\->condvar, handle, queue \& use Sereal (); # optional: faster serialization, may omit Storable \& \& use MCE::Hobo; # 1.808 or later on Windows \& use MCE::Shared; \& \& my $seq_a = MCE::Shared\->sequence( 1, 30 ); \& \& sub task { \& my ( $id ) = @_; \& while ( defined ( my $num = $seq_a\->next ) ) { \& print "$id: $num\en"; \& } \& } \& \& MCE::Hobo\->new( \e&task, $_ ) for 1 .. 2; \& MCE::Hobo\->waitall; \& \& threads\->exit(0) if $INC{"threads.pm"}; .Ve .SH "FCGI::PROCMANAGER DEMONSTRATIONS" .IX Header "FCGI::PROCMANAGER DEMONSTRATIONS" The demonstrations requires \s-1MCE 1.804\s0 to run. Otherwise, the \s-1MCE\s0 \f(CW\*(C`posix_exit\*(C'\fR option must be specified and set to 1. This applies to \s-1UNIX\s0 only and set automatically in 1.804 when \f(CW\*(C`(F)CGI.pm\*(C'\fR is present. .PP .Vb 1 \& #!/usr/bin/perl \& \& # http://127.0.0.1/cgi\-bin/test_mce1.fcgi \& # http://127.0.0.1/cgi\-bin/test_mce1.fcgi?size=8 \& \& use strict; \& use warnings; \& \& use MCE::Map max_workers => 3; \& \& use CGI::Fast; \& use FCGI::ProcManager; \& \& my $count = 0; \& \& my $proc_manager = FCGI::ProcManager\->new({ n_processes => 4 }); \& $proc_manager\->pm_manage(); \& \& while ( my $query = CGI::Fast\->new() ) { \& $proc_manager\->pm_pre_dispatch(); \& \& print "Content\-type: text/html\er\en\er\en"; \& print "$$: ", ++$count, "
\en"; \& print "
\en"; \& \& print "$_ = $ENV{$_}
\en" foreach sort keys %ENV; \& print "
\en"; \& \& my %params; \& \& foreach ( sort $query\->param() ) { \& $params{$_} = $query\->param($_); \& print $_, " = ", $params{$_}, "
\en"; \& } \& \& print "
\en"; \& \& my @ret = mce_map { "$$: ".( $_ * 2 ) } 1 .. $params{\*(Aqsize\*(Aq} || 8; \& \& print join("
\en", @ret), "
\en"; \& \& $proc_manager\->pm_post_dispatch(); \& } .Ve .PP Initializing \s-1MCE\s0 options before calling \f(CW\*(C`pm_manage\*(C'\fR is not recommended. The following is one way to do it and does the same thing. .PP .Vb 1 \& #!/usr/bin/perl \& \& # http://127.0.0.1/cgi\-bin/test_mce2.fcgi \& # http://127.0.0.1/cgi\-bin/test_mce2.fcgi?size=8 \& \& use strict; \& use warnings; \& \& use MCE::Map; \& \& use CGI::Fast; \& use FCGI::ProcManager; \& \& my ($first_time, $count) = (1, 0); \& \& my $proc_manager = FCGI::ProcManager\->new({ n_processes => 4 }); \& $proc_manager\->pm_manage(); \& \& while ( my $query = CGI::Fast\->new() ) { \& $proc_manager\->pm_pre_dispatch(); \& \& print "Content\-type: text/html\er\en\er\en"; \& print "$$: ", ++$count, "
\en"; \& print "
\en"; \& \& print "$_ = $ENV{$_}
\en" foreach sort keys %ENV; \& print "
\en"; \& \& my %params; \& \& foreach ( sort $query\->param() ) { \& $params{$_} = $query\->param($_); \& print $_, " = ", $params{$_}, "
\en"; \& } \& \& print "
\en"; \& \& if ( $first_time ) { \& MCE::Map\->init( max_workers => 3 ); \& } \& \& my @ret = mce_map { "$$: ".( $_ * 2 ) } 1 .. $params{\*(Aqsize\*(Aq} || 8; \& \& print join("
\en", @ret), "
\en"; \& \& $proc_manager\->pm_post_dispatch(); \& } .Ve .PP Sharing data is possible via \f(CW\*(C`MCE::Shared\*(C'\fR between \f(CW\*(C`FCGI\*(C'\fR and \f(CW\*(C`MCE\*(C'\fR workers. The following is a demonstration utilizing a shared counter variable which increments by one regardless of the \f(CW\*(C`FCGI\*(C'\fR worker serving the request. .PP .Vb 1 \& #!/usr/bin/perl \& \& # http://127.0.0.1/cgi\-bin/test_mce3.fcgi \& # http://127.0.0.1/cgi\-bin/test_mce3.fcgi?size=8 \& \& use strict; \& use warnings; \& \& use MCE::Map; \& use MCE::Shared; \& \& use CGI::Fast; \& use FCGI::ProcManager; \& \& # Shared variables must be defined before FCGI::ProcManager. \& my $count = MCE::Shared\->scalar( 0 ); \& my $first_time = 1; \& \& my $proc_manager = FCGI::ProcManager\->new({ n_processes => 4 }); \& $proc_manager\->pm_manage(); \& \& # Optional, the following statement must come after $pm\->pm_manage. \& MCE::Shared\->init(); # enables shared parallel\-IPC capabilities \& \& while ( my $query = CGI::Fast\->new() ) { \& $proc_manager\->pm_pre_dispatch(); \& \& print "Content\-type: text/html\er\en\er\en"; \& print "$$: ", $count\->incr(), "
\en"; \& print "
\en"; \& \& print "$_ = $ENV{$_}
\en" foreach sort keys %ENV; \& print "
\en"; \& \& my %params; \& \& foreach ( sort $query\->param() ) { \& $params{$_} = $query\->param($_); \& print $_, " = ", $params{$_}, "
\en"; \& } \& \& print "
\en"; \& \& if ( $first_time ) { \& MCE::Map\->init( max_workers => 3 ); \& $first_time = 0; \& } \& \& my @ret = mce_map { "$$: ".( $_ * 2 ) } 1 .. $params{\*(Aqsize\*(Aq} || 8; \& \& print join("
\en", @ret), "
\en"; \& \& $proc_manager\->pm_post_dispatch(); \& } .Ve .PP Resetting the environment is helpful during development. The shared-manager process stops immediately upon receiving the \f(CW\*(C`TERM\*(C'\fR signal. .PP .Vb 1 \& killall \-TERM perl\-fcgi perl\-fcgi\-pm ; service httpd restart .Ve .SH "TK DEMONSTRATIONS" .IX Header "TK DEMONSTRATIONS" The demonstrations requires \s-1MCE 1.805\s0 to run. Otherwise, the \s-1MCE\s0 \f(CW\*(C`posix_exit\*(C'\fR option must be specified and set to 1. This applies to \s-1UNIX\s0 only and set automatically in 1.805 when \f(CW\*(C`Tk.pm\*(C'\fR is present. .PP .Vb 1 \& #!/usr/bin/perl \& \& use strict; \& use warnings; \& \& use MCE; \& use Tk; \& \& my $mw = MainWindow\->new( \-title => \*(AqMCE/Tk Test\*(Aq ); \& \& $mw\->geometry( \*(Aq300x300\*(Aq ); \& $mw\->Button( \-text => "Test MCE", \-command => \e&test_mce )\->pack(); \& \& my $frame = $mw\->Frame\->pack( \-fill => \*(Aqx\*(Aq ); \& \& my $mce = MCE\->new( \& max_workers => 4, \& user_func => sub { \& my @args = @{ MCE\->user_args() }; \& print MCE\->pid(), ": $_\en"; \& }, \& )\->spawn; \& \& MainLoop; \& \& # Do not call $mce\->shutdown on Windows ($^O eq \*(AqMSWin32\*(Aq). \& # Workers terminate with the application. \& # \& # $mce\->shutdown(); \& \& print "Exiting...\en"; \& \& sub test_mce { \& $mce\->process({ \& user_args => [ \*(Aqarg1\*(Aq, \*(Aqarg2\*(Aq, \*(AqargN\*(Aq ], \& input_data => [ 1 .. 10 ], \& chunk_size => 1, \& }); \& } .Ve .PP The following demonstration does the same thing via MCE::Flow. .PP .Vb 1 \& #!/usr/bin/perl \& \& use strict; \& use warnings; \& \& use MCE::Flow max_workers => 4; \& use Tk; \& \& my $mw = MainWindow\->new( \-title => \*(AqMCE/Tk Test\*(Aq ); \& \& $mw\->geometry( \*(Aq300x300\*(Aq ); \& $mw\->Button( \-text => "Test MCE", \-command => \e&test_mce )\->pack(); \& \& my $frame = $mw\->Frame\->pack( \-fill => \*(Aqx\*(Aq ); \& \& sub task { \& my @args = @{ MCE\->user_args() }; \& print MCE\->pid(), ": $_\en"; \& } \& \& MainLoop; \& \& print "Exiting...\en"; \& \& sub test_mce { \& MCE::Flow\->init( \& user_args => [ \*(Aqarg1\*(Aq, \*(Aqarg2\*(Aq, \*(AqargN\*(Aq ], \& chunk_size => 1 \& ); \& MCE::Flow\->run( \e&task, [ 1 .. 10 ] ); \& } .Ve .PP MCE::Hobo 1.804 or later is another possibility if running on a \s-1UNIX\s0 platform. .PP .Vb 1 \& #!/usr/bin/perl \& \& use strict; \& use warnings; \& \& use MCE::Hobo; \& use Tk; \& \& my $mw = MainWindow\->new( \-title => \*(AqMCE/Tk Test\*(Aq ); \& \& $mw\->geometry( \*(Aq300x300\*(Aq ); \& $mw\->Button( \-text => "Test MCE", \-command => \e&test_mce )\->pack(); \& \& my $frame = $mw\->Frame\->pack( \-fill => \*(Aqx\*(Aq ); \& \& sub task { \& my @args = @_; \& print MCE::Hobo\->pid(), ": $_\en"; \& } \& \& MainLoop; \& \& print "Exiting...\en"; \& \& sub test_mce { \& MCE::Hobo\->create(\e&task, \*(Aqarg1\*(Aq, \*(Aqarg2\*(Aq, \*(AqargN\*(Aq) for ( 1 .. 4 ); \& MCE::Hobo\->waitall(); \& } .Ve .SH "INDEX" .IX Header "INDEX" \&\s-1MCE\s0, MCE::Core .SH "AUTHOR" .IX Header "AUTHOR" Mario E. Roy,