use strict; use threads; use Thread::Queue; my $PingQueue = Thread::Queue->new; my $PingResQueue = Thread::Queue->new; my $requestsinprocess = 0; my $ping = 'ping -c 1'; # Ping for Linux $ping = 'ping -n 1' if ( $^O eq 'MSWin32'); # Ping for Windows foreach my $i ( 0..7 ) { # Create some threads my $pingthread = threads->new(\&Ping,$i)->detach; } while ( 1 ) { # Check for finished pings if ( $requestsinprocess > 0 ) { # Check if there is anything on PingResQueue while ( defined ( my $pingres = $PingResQueue->dequeue_nb ) ) { # with a non blocking dequeue of PingResQueue print "$pingres\n"; $requestsinprocess--; } } if ( $requestsinprocess == 0 ) { # Start a new round with pings foreach ( 0..17 ) { $PingQueue->enqueue("127.0.0.1"); # Put ip on PingQueue, it's dequeued in &Ping() $requestsinprocess++; } } select( undef, undef, undef, 0.1 ); # Sleep a while } exit 0; sub Ping { my $id = shift; my $tolalping = 0; while (my $ip = $PingQueue->dequeue) { # Block here and wait for an ip on PingQueue my $pingres = `$ping $ip`; # Do a system call $PingResQueue->enqueue("$id " . $tolalping++); # Put something on PingResQueue to be dequed in the main thread } }