Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run external command in parallel using AnyEvent and Perl

I'm new to Perl 5 asynchronous processes and find it exciting that CPAN offers similar support that we can do in Node.js with AnyEvent, IO::Async, etc. However, the tutorial provides a few examples for complicated stuff. What I need is only to run an external system command in parallel using AnyEvent.

Am I doing it correctly in the example below to zip a number of files asynchronously? Please don't raise a concern about running the system command zip instead of using CPAN modules; the example is purely to demonstrate the idea of running an asynchronous process...

#!/bin/env perl
use strict; 
use AnyEvent;
use AnyEvent::Util;

my $s1    = time;

my $quit_program = AnyEvent->condvar(
    cb => sub {
        warn "Done async";
    }
);

my $result;
$quit_program->begin( sub { shift->send($result) } );

for my $file (@files) {
    $quit_program->begin;

    my $cv; $cv = run_cmd [qw(zip), "${file}.zip", $file],
                "<" , "/dev/null",
                ">" , "/dev/null",
                "2>", "/dev/null";

    $cv->cb (sub {
        shift->recv and die "command failed";

        # undef $cv;
        $quit_program->end;
    });
}

$quit_program->end;   # end loop
my $foo = $quit_program->recv;
say "Total elapsed time: ", time - $s1, " ms";
like image 909
est Avatar asked Oct 20 '22 09:10

est


1 Answers

I assume you mean AnyEvent::Util and not AnyEvent::Tool.

Otherwise, I haven't tried out your program, but it looks like a textbook example of using condvars and run_cmd to me. It certainly is close to what I would write myself (I am the author of AnyEvent), gets the tricky parts right (having an outer begin/end in case @files is empty), does error checking and so on.

So if you ask me, you actually did read the docs and used your knowledge to pass the exam :)

like image 142
Remember Monica Avatar answered Oct 23 '22 05:10

Remember Monica