我对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); # I hoped this may be usefull to limit # of concurrent threads while ( my $phost = $pq->dequeue() ) { $semaphore->down(); threads->create( { 'stack_size' => 32 * 4096 }, \&ping_th, $phost ); } sub ping_th { $rq->enqueue( $_[0] ) if $ping->ping( $_[0], 1 ); $semaphore->up(); threads->detach(); } $rq->enqueue(undef); while ( my $alive_ip = $rq->dequeue() ) { print $alive_ip, "\n"; }
我找不到一个关于threads-> detach()应该如何在一个线程子程序中工作的完全全面的描述,并认为这可能有用......而且它确实 - 如果我在主程序(线程)中做了一些延伸它的生命周期(睡眠很好),所以所有分离的线程完成并将它们的部分排入我的$ rq,否则它将运行一些线程将其结果收集到队列并退出警告,如:
Perl exited with active threads: 5 running and unjoined 0 finished and unjoined 0 running and detached
使主程序暂时"休眠"一段时间,再一次看起来很愚蠢 - 有没有办法让线程完成他们的东西并且只能在实际的thread-> detach()调用之后分离?到目前为止,我的猜测是,一旦创建了线程,子线程中的threads-> detach()就会应用,所以这不是方法.我用CentOSs老版本v5.10.1尝试了这个.这应该改变现代v5.16或v5.18(usethreads-compiled)?