http://www.perlmonks.org?node_id=392426


in reply to Multi-threading ping of a list of hosts.....Again!

Here is some working multi-threaded ping code I wrote a while back. Works on Win32.
#!/usr/bin/perl -w # Parallel Pinger... use strict; use threads; use Thread::Queue; use Net::Ping; my $master = $$; my $verbose = $ARGV[0] eq q(-v); my $RequestQ = Thread::Queue->new; my $ResultQ = Thread::Queue->new; my $threadcount = 20; my @kids; # Generate list of hosts to ping my @targets; foreach my $target (1..95) { $RequestQ->enqueue ('10.2.56.' . $target); } for (0..($threadcount - 1)){ $RequestQ->enqueue(undef); push @kids, threads->new(\&Ping_it, $_); } foreach (threads->list){ $_->join; } $ResultQ->enqueue(undef); # Last item while (my $target = $ResultQ->dequeue){ print " $target\n"; } ############################################# sub Ping_it{ my ($work_count, $miss_count); my $t = shift; my $pinger = Net::Ping->new('icmp', 1); while (my $target = $RequestQ->dequeue){ $work_count ++; my $retval = 0; $verbose and print "Child $target started\n"; if($pinger->ping($target)) { # PING! Throw it in the FIFO $verbose and print "Found $target!\n"; $retval=1 } else { warn "Thread $t $target: $!\n"; $verbose and print "No response from $target\n"; $retval=0; $miss_count++; } $ResultQ->enqueue ($target . "=" . $retval); threads->yield(); $verbose and print "Child $target exiting\n"; } $pinger->close(); $ResultQ->enqueue("Thread $t processed $work_count, missed $miss_co +unt"); }

    Earth first! (We'll rob the other planets later)