use MCE::Simple -strict, max_workers => 4;
MCE::Simple->init(
# mce options
user_begin => sub {
MCE->say("hello from ", MCE->wid);
},
# spawn options
on_finish => sub {
my ( $pid, $exit, $ident, $signal, $error, @ret ) = @_;
say "@_";
},
);
mce_foreach my $i ( 1..10 ) {
MCE->say(MCE->wid, ": $i * 2 = ", $i * 2);
}
spawn "Hello", sub { "one" };
spawn "There", sub { "two" };
foreach my $ident (qw/foo baz/) {
spawn $ident, sub {
my $text = "something from $$";
};
}
sync;
# clear or set options
MCE::Simple->init();
sub fib {
my $n = shift;
return $n if $n < 2;
spawn my $x = fib($n - 1);
spawn my $y = fib($n - 2);
sync $x;
sync $y;
return $x + $y;
}
say "fib(20) = ", fib(20);
####
$ perl demo.pl
hello from 1
hello from 2
hello from 3
hello from 4
3: 2 * 2 = 4
4: 1 * 2 = 2
2: 3 * 2 = 6
3: 5 * 2 = 10
4: 6 * 2 = 12
1: 4 * 2 = 8
4: 7 * 2 = 14
3: 8 * 2 = 16
2: 9 * 2 = 18
1: 10 * 2 = 20
10792 0 Hello 0 one
10793 0 There 0 two
10794 0 foo 0 something from 10794
10795 0 baz 0 something from 10795
fib(20) = 6765
##
##
use MCE::Simple -strict, max_workers => 16;
use MCE::Semaphore;
use Time::HiRes 'time';
my $start = time;
my $sem = MCE::Semaphore->new(8);
mce_foreach_s ( 1 .. 1_000_000 ) {
$sem->down;
$sem->up;
}
printf "%0.3f seconds\n", time - $start;
##
##
mce_foreach_f ("/path/to/file") {
MCE->print($_);
}
# what about file handles? no problem...
open my $fh, "<", "/tmp/infile.txt" or die "open error: $!";
mce_foreach_f my $line ( $fh ) {
MCE->print($line);
}
close $fh;