This shows two other alternatives of parallel processing (not explicitly using fork).
Save this as MyChameleon.pm:
package MyChameleon;
use strict;
use warnings;
use threads;
$| = 1; # autoflush STDOUT
my $used_as_script = not caller();
if ($used_as_script) {
print "Start script\n";
my $thread_to_do = threads->create( \&to_do, 'thread', 5 );
my $thread_sys = threads->create(
sub {
system $^X, "-MMyChameleon", "-e", "MyChameleon::to_do('sy
+stem')";
}
);
to_do( 'script', 3 );
$thread_to_do->join;
$thread_sys->join;
exit;
}
sub to_do {
my ( $tag, $times ) = @_;
$times //= 10;
print "$tag: Hello World!\n";
map { print "$tag ($_)\n"; sleep 1 } ( 1 .. $times );
print "$tag: is done\n";
}
!!1;
Run it like this: “perl MyChameleon.pm”.
See also How a script becomes a module
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|