我对perl(以及编程也是)很新,并且在过去的几周内一直在玩线程,到目前为止,我明白使用它们执行一些类似的并行任务是令人沮丧的 - 如果你的线程数量,内存消耗是无法控制的取决于一些输入值,并简单地限制该数字和做一些临时连接似乎非常愚蠢.所以我试图欺骗线程通过队列返回一些值,然后分离这些线程(并没有实际加入它们) - 这是一个并行ping的例子:
#!/usr/bin/perl
#
use strict;
use warnings;
use threads;
use NetAddr::IP;
use Net::Ping;
use Thread::Queue;
use Thread::Semaphore;
########## get my IPs from CIDR-notation #############
my @ips;
for my $cidr (@ARGV) {
my $n = NetAddr::IP->new($cidr);
foreach ( @{ $n->hostenumref } ) {
push @ips, ( split( '/', $_ ) )[0];
}
}
my $ping = Net::Ping->new("icmp");
my $pq = Thread::Queue->new( @ips, undef ); # ping-worker-queue
my $rq = Thread::Queue->new(); # response queue
my $semaphore = Thread::Semaphore->new(100); …Run Code Online (Sandbox Code Playgroud)