Created
April 18, 2017 08:36
-
-
Save mindc/06c26f96159c42b024aa1194390a8925 to your computer and use it in GitHub Desktop.
Parallel pings using threads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use strict; | |
use warnings; | |
use threads; | |
use threads::shared; | |
use Thread::Queue; | |
use JSON::XS; | |
use Net::Ping; | |
use Data::Dumper; | |
my @data = qw( | |
8.8.8.8 | |
8.8.4.4 | |
google.com | |
); | |
my @result = parallel3( | |
2, | |
sub { | |
my $ping = new Net::Ping('icmp'); | |
$ping->hires(); | |
return [ $ping->ping(shift,0.5) ]; | |
}, | |
@data | |
); | |
print Dumper \@result; | |
exit; | |
sub parallel3 { | |
my ( $max, $handler, @args ) = @_; | |
my $json = JSON::XS->new; | |
my $q = Thread::Queue->new; | |
return () if @args == 0; | |
if ( $max > @args ) { $max = @args } | |
$q->limit = $max; | |
my @out : shared; | |
for ( 1..$max ) { | |
threads->create(sub { | |
while ( defined(my $d = $q->dequeue()) ) { | |
my ($result) = $handler->($d->[1]); | |
$out[$d->[0]] = $json->allow_nonref->encode($result); | |
} | |
}); | |
} | |
my $idx = 0; | |
foreach ( @args ) { | |
$q->enqueue([$idx++,$_]); | |
} | |
$q->end; | |
foreach ( threads->list ) { | |
$_->join; | |
} | |
return map { $json->allow_nonref->decode($_) } @out; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment