How can I use IO::Async with an array as input? - perl

I have this loop:
foreach my $element ( #array ) {
my $result = doSomething($element);
}
Since it doesn't matter that the array is processed in order, and the script runs long, I'd like run doSomething() asynchronously.
I am looking at IO::Async for this, but I can't seem to find an example where the input to the loop is a simple array as above. The example seem to focus on open sockets, STDIN, etc.
Here is the example given, showing feeding data to the loop via STDIN:
$loop->add( IO::Async::Stream->new_for_stdin(
on_read => sub {
my ( $self, $buffref, $eof ) = #_;
while( $$buffref =~ s/^(.*)\n// ) {
print "You typed a line $1\n";
}
return 0;
},
) );
How can I feed it the array elements instead?

As commented by #StefanBecker, the simplest way to handle this with IO::Async is by using an IO::Async::Function.
From the docs :
This subclass of IO::Async::Notifier wraps a function body in a collection of worker processes, to allow it to execute independently of the main process.
In the IO::Async framework, the typical use case for IO::Async::Function is when a blocking process needs to be executed asynchronously.
Disclaimer : please note that, as commented also by #zdim, IO::Async might not be the best fit for your use case. A pure process parallelizer such as Parallel::ForkManager would probably be your best option here, as it basically implements the same functionality (forking and executing in parallel), yet in a much more straight-forward fashion. One of the main differentiating factor of IO::Async comes with its I/O multiplexing capabilities, that you are seemingly not using here.
But since you namely asked for IO::Async, here is an example of such implementation : I turned doSomething into a dummy method that just waits the amount of time given as argument. This allows you to observe the effect of asynchronous execution.
use strict;
use warnings;
use IO::Async::Function;
use IO::Async::Loop;
use Future;
# dummy sub
sub doSomething {
my ( $delay ) = #_;
print "start waiting $delay second(s)\n";
sleep $delay;
print "done sleeping $delay second(s)\n";
return $delay;
}
# prepare the function for execution
my $loop = IO::Async::Loop->new;
my $function = IO::Async::Function->new( code => sub { return doSomething($_[0]) } );
$loop->add($function);
# trigger asynchronous processing
my #array = qw/5 2 4 0/;
my #futures = map { $function->call( args => [ $_ ] ) } #array;
# safely wait for all ops to complete
Future->wait_all(#futures)->await;
print "all done !\n";
This yields :
start waiting 5 second(s)
start waiting 2 second(s)
start waiting 4 second(s)
start waiting 0 second(s)
done sleeping 0 second(s)
done sleeping 2 second(s)
done sleeping 4 second(s)
done sleeping 5 second(s)
all done !
NB1 : Future->wait_all(#futures)->await could also be written $_->get for #futures, however the first expression, that uses convergent Futures, has the advantages that it will never fail, even if an underlying call actually dies.
NB2 : many options are available in IO::Async::Function and Future to handle errors, manage the number of workers and their behavior, and so on. Check out the docs for more details...

Related

Parallel::ForkManager takes too much time to start 'finish' function

I use the regular Parallel::ForkManager module in Perl. I execute around 10 children processes. 'passes_thresholds' function takes few milliseconds or nanoseconds (checked it). In case I run all processes one by one (without Parallel::ForkManager) the whole process took 80-250 milliseconds. In case I run them as parallel, the whole process takes at least 1 second. I found that the Fork spends 1 second to start the 'finish' function. I put a timer when the child process finished his job and should go to 'finish'- function. One second is too much for my development.
sub parallel_execute {
my $this = shift;
foreach my $a (#a_array) {
my $pid = $this->{fork_manager}->start and next;
my $res = $a->passes_thresholds();
$a->{timer} = Benchmark::Timer->new();
$svc->{timer}->start;
$this->{fork_manager}->finish(0,{a => $a, plugin_result => $res});
}
}
$this->{fork_manager}->run_on_finish( sub {
my ($pid, $exit_code, $ident, $exit_signal, $core_dump, $data_structure_reference) = #_;
my $a = $data_structure_reference->{a};
if (exists $a->{timer}) {
$a->{timer}->stop;
debug "took: " . $a->{timer}->report;
}
});
Do you have any idea why it took at least 1 second to start the 'finish' command?
(I am using Unix server, and perl 5.10)
Thanks you all, i found the problem. ForManager module has 'waitpid_blocking_sleep' parameter, which defined as 1 second by default. There is a function called 'set_waitpid_blocking_sleep' which we can defined this parameter (sleep time). We can set zero or fraction of seconds. I set this paramter to zero and it fixed my issue.
The on_finish callback is only called when P::FM reaps a child, and P::FM only reaps a child under three conditions:
When $pm->start is called and the number of children that have been started but not reaped is equal to the maximum.
When $pm->reap_finished_children is called.
When $pm->wait_all_children is called.
There could be an arbitrarily long delay between a child exiting and one the above events. Adding the following to your program should eliminate that delay:
$SIG{CHLD} = sub { $pm->reap_finished_children };
By the way, if the work performed by your child only takes "a few milliseconds or nanoseconds", you are actually slowing things down by using P::FM. Data passed to finish gets serialized and written to disk, then read from the disk and deserialized for the on_finish callback!

How to wait for child process to set variable in parent process?

use Parallel::ForkManager;
my $number_running = 0;
my $pm = new Parallel::ForkManager(30);
$pm->run_on_start( sub { ++$number_running; } );
$pm->run_on_finish( sub { --$number_running; } );
for (my $i=0; $i<=100; $i++)
{
if ($number_running == 5) { while ($number_running > 0) {} } # waits forever
$pm->start and next;
print $i;
$pm->finish;
}
The above code uses Parallel::ForkManager to execute code in a for loop using parallel processes. It is counting how many child processes are running and setting the $number_running variable accordingly. Once 5 child processes are running, I would like it to wait until 0 child processes are running before continuing.
The first line in the for loop is designed to achieve this but it waits forever on that line. It's like the change to the variable made by the child processes is not available to that line of code. What am I doing wrong? Note: I am aware of wait_all_children but I don't want to use it.
Short   The callback run_on_finish normally doesn't get triggered for every child's exit, so $number_running doesn't get reduced and thus it can't control the loop. Ways to fix this:
use reap_finished_children in order to communicate as individual children exit, so that run_on_finish indeed gets to run as each child exits
use wait_for_available_procs to wait for the whole batch to finish before starting a new set of processes
As for the title ("How to wait for child process to set variable in parent process?"), a child process cannot set anything in the parent, nor could parent in the child. They must communicate to accord actions, using some form of Inter-Process-Communication (IPC). This module provides some of that, and a few methods useful for this question are outlined above.
The callback run_on_start runs with every new process and the counter is incremented. But the callback run_on_finish is never triggered so the counter is never decremented. Thus once it reaches 5 the code sits in the while loop. Note that a parent and children are separate processes which thus don't know about each other's variables and cannot change them.
The callback run_on_finish is commonly triggered by having wait_all_children after all processes were forked. Its job is also done
when maximum number of processes run and one exits. This is done in start by a call to wait_one_child (which calls on_finish, see below).
Or, this can be done at will by calling reap_finished_children method
This is a non-blocking call to reap children and execute callbacks independent of calls tostart or wait_all_children. Use this in scenarios where start is called infrequently but you would like the callbacks executed quickly.
This resolves the main concern of how to communicate as individual children exit (as clarified in comments), and not by wait_all_children.
Here is an example of how to use it so that the callback runs right as a child exits. A good deal of the code is merely for diagnostics (prints).
use warnings;
use strict;
use feature 'say';
use Parallel::ForkManager;
$| = 1;
my $total_to_process = 3; # only a few for this test
my $number_running = 0;
my #ds;
my $pm = Parallel::ForkManager->new(30);
$pm->run_on_start( sub {
++$number_running;
say "Started $_[0], total: $number_running";
});
$pm->run_on_finish( sub {
--$number_running;
my ($pid, $code, $iden, $sig, $dump, $rdata) = #_;
push #ds, "gone-$pid";
say "Cleared $pid, ", ($rdata->[0] // ''), ($code ? " exit $code" : '');
});
foreach my $i (1 .. $total_to_process)
{
$pm->start and next;
run_job($i);
$pm->finish(10*$i, [ "kid #$i" ]);
}
say "Running: ", map { "$_ " } $pm->running_procs; # pid's of children
# Reap right as each process exits, retrieve and print info
my $curr = $pm->running_procs;
while ($pm->running_procs)
{
$pm->reap_finished_children; # may be fewer now
if ($pm->running_procs < $curr) {
$curr = $pm->running_procs;
say "Remains: $number_running. Data: #ds";
}
sleep 1; # or use Time::HiRes::sleep 0.1;
}
sub run_job {
my ($num) = #_;
my $sleep_time = ($num == 1) ? 1 : ($num == 2 ? 10 : 20);
sleep $sleep_time;
say "\tKid #$num slept for $sleep_time, exiting";
}
Use of this method is equivalent to calling waitpid -1, POSIX::WNOHANG in a loop after fork. This forks fewer than the max (30) processes to see output more easily and demonstrate that the callback runs right as a child exits. Change these numbers to see its full operation.
A child process exits with 10*$i, so to be able to track children processes in the output. The data returned in an anonymous array [...] is a string identifying the child process. As soon as the reap_finished_children call completes the $number_running is reduced, in the callback. This is the reason for having the $curr variable, again for diagnostics.
This prints
start: Started 4656, running: 1
start: Started 4657, running: 2
start: Started 4658, running: 3
Running: 4656 4658 4657
Kid #1 slept for 1, exiting
Cleared 4656, kid #1 exit 10
Remains: 2. Data: gone-4656
Kid #2 slept for 10, exiting
Cleared 4657, kid #2 exit 20
Remains: 1. Data: gone-4656 gone-4657
Kid #3 slept for 20, exiting
Cleared 4658, kid #3 exit 30
Remains: 0. Data: gone-4656 gone-4657 gone-4658
The direct question is of how to wait for the whole batch to finish before starting a new one. This can be done directly by wait_for_available_procs($n)
Wait until $n available process slots are available. If $n is not given, defaults to 1.
If $MAX is used for $n, that many slots will become available only once the whole batch completed. What to use for $n can also be decided at runtime.
Some details of module's operation
When a child exits the SIGCHLD signal is sent to the parent, which it must catch in order to know that the child is gone (and to avoid zombies, in the first place). This is done by using wait or waitpid, in code or in the SIGCHLD handler (but only at one place). See fork, Signals in perlipc, waitpid and wait.
We see from P::FM's source that this is done in wait_one_child (via _waitpid sub)
sub wait_one_child { my ($s,$par)=#_;
my $kid;
while (1) {
$kid = $s->_waitpid(-1,$par||=0);
last if $kid == 0 || $kid == -1; # AS 5.6/Win32 returns negative PIDs
redo if !exists $s->{processes}->{$kid};
my $id = delete $s->{processes}->{$kid};
$s->on_finish( $kid, $? >> 8 , $id, $? & 0x7f, $? & 0x80 ? 1 : 0);
last;
}
$kid;
};
which is used in wait_all_children
sub wait_all_children { my ($s)=#_;
while (keys %{ $s->{processes} }) {
$s->on_wait;
$s->wait_one_child(defined $s->{on_wait_period} ? &WNOHANG : undef);
};
}
The method reap_finished_children used above is a synonym for this method.
The method wait_one_child that gets the signal is used by start to reap child processes when maximum number of processes is filled and one exits. This is how the module knows when it can start another process and respect its maximum. (It is also used by a few other routines that wait for processes.
). And this is when run_on_finish gets triggered, by $s->on_finish( $kid, ... )
sub on_finish {
my ($s,$pid,#par)=#_;
my $code=$s->{on_finish}->{$pid} || $s->{on_finish}->{0} or return 0;
$code->($pid,#par);
};
The callback is in the coderef $code, retrieved from the object's on_finish key, which itself is set in the sub run_on_finish. This is how the callback is set up, once that sub runs.
The methods availed to the user for this are wait_all_children and reap_finished_children.
Since none of this is used in the posted code the $number_running is not getting updated so while is an infinite loop. Recall that the variable $number_running in the parent cannot be directly changed by child processes.

Execution time for each forked process perl

I am executing a script and have forked it to run parallel.
I notice that some of the processes take more time to execute and want to keep a track of each process when it started and ended.
Right now, I am printing the time to the terminal while executing but its not easy to determine which process is taking time to execute.
Is there a way to track it while using Perl Parallel:ForkManager?
It is unclear whether you are looking for real-time feedback on the processes that are running or whether you are just looking to understand if one child took longer at the end. Assuming you just want to know a final result, the following will suffice:
Use Benchmark, and the run_on_finish callback of Parallel::ForkManager. Something like this may work for you. We store the start time of the forked process when we fork it. When the child exits, Parallel::ForkManager will call the run_on_finish callback with the pid that exited. You can then store the end time of the child and then calculate the differences with Benchmark.
use Benchmark;
use Parallel::ForkManager;
my $max_forks = 5;
my $mgr = Parallel::ForkManager->new( $max_forks );
my %times;
$mgr->run_on_finish(sub {
my $pid = shift;
$times{$pid}->[1] = Benchmark->new; # end time mark
});
for ( 1 .. $max_forks+1 ) { # N+1 to show that wait time isn't included.
if (my $pid = $mgr->start) { # Parent
$times{$pid} = [Benchmark->new, undef]; #start time
next;
}
srand(time^$$); # don't do this in real-world, perldoc srand
my $sleep = int(rand(9));
say "$$ sleeping $sleep";
sleep ($sleep);
$mgr->finish;
}
$mgr->wait_all_children;
foreach my $pid (keys %times) {
say "Pid: $pid, ProcessTime: ", timestr(timediff($times{$pid}->[1], $times{$pid}->[0]));
}
Please refer to Benchmark perldocs for details on the output you can calculate and further functions.
- Mike

Trying to use fork to do a seemingly simple task, but failing miserably

So, basically I have a very large array that I need to read data from. I want to be able to do this in parallel; however, when I tried, I failed miserably. For the sake of simplicity, let's say I have an array with 100 elements in it. My idea was to partition the array into 10 equals parts and try to read them in parallel (10 is arbitrary, but I don't know how many processes I could run at once and 10 seemed low enough). I need to return a computation (new data structure) based off of my readings from each partition, but I am NOT modifying anything in the original array.
Instead of trying the above exactly, I tried something simpler, but I did it incorrectly, because it didn't work in any capacity. So, then I tried to simply use child processes to push to a an array. The code below is using Time::HiRes to see how much faster I can get this to run using forking as opposed to not, but I'm not at that point yet (I'm going to be testing that when I have closer to a few million entries in my array):
use strict;
use warnings;
use Time::HiRes;
print "Starting main program\n";
my %child;
my #array=();
my $counter=0;
my $start = Time::HiRes::time();
for (my $count = 1; $count <= 10; $count++)
{
my $pid = fork();
if ($pid)
{
$child{$pid}++;
}
elsif ($pid == 0)
{
addToArray(\$counter,\#array);
exit 0;
}
else
{
die "couldnt fork: $!\n";
}
}
while (keys %child)
{
my $pid = waitpid(-1,0);
delete $child{$pid};
}
my $stop = Time::HiRes::time();
my $duration = $stop-$start;
print "Time spent: $duration\n";
print "Size of array: ".scalar(#array)."\n";
print "End of main program\n";
sub addToArray
{
my $start=shift;
my $count=${$start};
${$start}+=10;
my $array=shift;
for (my $i=$count; $i<$count +10; $i++)
{
push #{$array}, $i;
}
print scalar(#{$array})."\n";
}
NB: I used push in lieu of ${$array}[$i]=$i, because I realized that my $counter wasn't actually updating, so that would never work with this code.
I assume that this doesn't work because the children are all copies of the original program and I'm never actually adding anything to the array in my "original program". On that note, I'm very stuck. Again, the actual problem that I'm actually trying to solve is how to partition my array (with data in it) and try to read them in parallel and return a computation based off of my readings (NOTE: I'm not going to modify the original array), but I'm never going to be able to do that if I can't figure out how to actually get my $counter to update. I'd also like to know how to get the code above to do what I want it to do, but that's a secondary goal.
Once I can get my counter to update correctly, is there any chance that another process would start before it updates and I wouldn't actually be reading in the entire array? If so, how do I account for this?
Please, any help would be much appreciated. I'm very frustrated/stuck. I hope there is an easy fix. Thanks in advance.
EDIT: I attempted to use Parallel::ForkManager, but to no avail:
#!/usr/local/roadm/bin/perl
use strict;
use warnings;
use Time::HiRes;
use Parallel::ForkManager;
my $pm = Parallel::ForkManager->new(10);
for (my $count = 1; $count <= 10; $count++)
{
my $pid = $pm->start and next;
sub1(\$counter,\#array);
$pm->finish; # Terminates the child process
}
$pm->wait_all_children;
I didn't include the other extraneous stuff, see above for missing code/sub... Again, help would be much appreciated. I'm very new to this and kind of need someone to hold my hand. I also tried to do something with run_on_start and run_on_finish, but they didn't work either.
Your code has two issues: Your child processes share no data, and you would have a race condition if forked processes would share data. The solution is to use threads. Any possibility for race conditions can be eliminated by partitioning the data in the parent thread, and of course, by not using shared data.
Threads
Threads in Perl behave similar to forking: by default, there is no shared memory. This makes using threads quite easy. However, each thread runs it own perl interpreter, which makes threads quite costly. Use sparingly.
First, we have to activate threading support via use threads. To start a thread, we do threads->create(\&code, #args), which returns a thread object. The code will then run in a separate thread, and will be invoked with the given arguments. After the thread has finished execution, we can collect the return value by calling $thread->join. Note: The context of the threaded code is determined by the create method, not by join.
We could mark variables with the :shared attribute. Your $counter and #array would be examples for this, but it is generally better to pass explicit copies of data around than to use shared state (disclaimer: from a theoretical standpoint, that is). To avoid race conditions with the shared data, you'd actually have to protect your $counter with a semaphore, but again, there is no need for shared state.
Here is a toy program showing how you could use threads to parallelize a calculation:
use strict;
use warnings;
use threads;
use 5.010; # for `say`, and sane threads
use Test::More;
# This program calculates differences between elements of an array
my #threads;
my #array = (1, 4, 3, 5, 5, 10, 7, 8);
my #delta = ( 3, -1, 2, 0, 5, -3, 1 );
my $number_of_threads = 3;
my #partitions = partition( $#array, $number_of_threads );
say "partitions: #partitions";
for (my $lower_bound = 0; #partitions; $lower_bound += shift #partitions) {
my $upper_bound = $lower_bound + $partitions[0];
say "spawning thread with [#array[$lower_bound .. $upper_bound]]";
# pass copies of the values in the array slice to new thread:
push #threads, threads->create(\&differences, #array[$lower_bound .. $upper_bound]);
# note that threads->create was called in list context
}
my #received;
push #received, $_->join for #threads; # will block until all are finished
is_deeply \#received, \#delta;
done_testing;
# calculates the differences. This doesn't need shared memory.
# note that #array could have been safely accessed, as it is never written to
# If I had written to a (unshared) variable, these changes would have been thread-local
sub differences {
say "Hi from a worker thread, I have ", 0+#_, " elements to work on";
return map $_[$_] - $_[$_-1], 1 .. $#_;
# or more readable:
# my #d;
# for my $i (1 .. $#_) {
# push #d, $_[$i] - $_[$i-1];
# }
# return #d;
}
# divide workload into somewhat fair parts, giving earlier threads more work
sub partition {
my ($total, $parts) = #_;
my $base_size = int($total / $parts);
my #partitions = ($base_size) x $parts;
$partitions[$_-1]++ for 1 .. $total - $base_size*$parts;
return #partitions;
}
A note on the number of threads: This should depend on the number of processors of your system. If you have four cores, more than four threads don't make much sense.
If you're going to use child processes after forking, each child process is autonomous and has its own copy of the data in the program as of the time it was forked from the main program. The changes made by the child in its own memory have no effect on the parent's memory. If you need that, either you need a threading Perl and to use threads, or you need to think again — maybe using shared memory, but locating Perl data into the shared memory might be tricky.
So, one option is to read all the data into memory before forking off and having the children work on their own copies of the data.
Depending on the structure of the problem, another possibility might be to have each child read and work on a portion of the data. This won't work if each child must have access to all the data.
It isn't clear how much speed up you'll get through threading or forking if the threads or processes are all tied up reading the same file. Getting the data into memory may be best treated as a single-threaded (single-tasking) operation; the parallelism can spring into effect — and yield benefits — once the data is in memory.
There are some CPAN modules that makes your life easier. One of them is Parallel::ForkManager, which is a simple parallel processing fork manager
So, after my struggle, here's the fix:
EDIT: THIS DOES NOT ACCOMPLISH WHAT I WANTED TO DO
#!/usr/local/roadm/bin/perl
use strict;
use warnings;
use Time::HiRes;
use Parallel::ForkManager;
print "Starting main program\n";
my #array=();
my $counter=0;
my $start = Time::HiRes::time();
my $max_processes=20;
my $partition=10;
my $max_elements=100;
my $pm = Parallel::ForkManager->new($max_processes);
$pm->run_on_start( sub {
my ($pid, $exit_code, $ident) = #_;
sub1(\$counter,\#array);
});
while ($counter < $max_elements)
{
my $pid = $pm->start and next;
$pm->finish; # Terminates the child process
}
$pm->wait_all_children;
my $stop = Time::HiRes::time();
my $duration = $stop-$start;
print "Time spent: $duration\n";
print "Size of array: ".scalar(#array)."\n";
print "\nEnd of main program\n";
sub sub1 {
my $start=shift;
my $count=${$start};
${$start}+=$partition;
my $array=shift;
for (my $i=$count; $i<$count + $partition; $i++)
{
push #{$array}, $i;
}
return #{$array};
}

Perl running simultaneous routines

I am running trying to run two sub routines at once in perl. What is the best way I can about doing that? For example:
sub 1{
print "im running";
}
sub 2{
print "o hey im running too";
}
How can I execute both routines at once?
Use threads.
use strict;
use warnings;
use threads;
sub first {
my $counter = shift;
print "I'm running\n" while $counter--;
return;
}
sub second {
my $counter = shift;
print "And I'm running too!\n" while $counter--;
return;
}
my $firstThread = threads->create(\&first,15); # Prints "I'm running" 15 times
my $secondThread = threads->create(\&second,15); # Prints "And I'm running too!"
# ... 15 times also
$_->join() foreach ( $firstThread, $secondThread ); # Cleans up thread upon exit
What you should pay attention to is how the printing is interleaved irregularly. Don't try to base any calculations on the false premise that the execution order is well-behaved.
Perl threads can intercommunicate using:
shared variables (use threads::shared;)
queues (use Thread::Queue;)
semaphores (use Thread::Semaphore;)
See perlthrtut for more information and an excellent tutorial.
I actually didn't realise that Perl can do this, but what you need is multithreading support:
http://search.cpan.org/perldoc?threads
Either that, or fork two processes, but that would be a bit harder to isolate the invocation of the subroutine.