Har*_*rry 1 perl multithreading
看起来thread_sleep没有正确结束。
我可以使用线程队列、信号量等来处理它,但我对这里可能出现的问题感兴趣。
这段代码永远不会结束,因为threads->list()大小永远不会减少。
use strict;
use warnings;
use Thread;
my @threads;
my $count = 0;
while ( scalar( @threads ) < 10 ) {
my $thr = threads->create( 'thread_sleep' );
push @threads, $thr;
$count++;
print "Spawned Thread nr. $count\n";
while ( threads->list() > 4 ) {
print "too many threads, sleeping a second...\n";
sleep( 1 );
}
}
sub thread_sleep {
sleep( 5 );
}
Run Code Online (Sandbox Code Playgroud)
小智 5
线程的工作方式很像进程——在一个线程退出后,它作为一个“僵尸”线程留在线程列表中,直到另一个线程(不一定是它的父线程)调用$thr->join来收集它的返回值。
你没有$thr->join在任何地方打电话,所以这些线程堆积如山。您可以使用threads->list(threads::joinable)来检查哪些线程已经退出并且现在可以加入。
(或者,考虑使用它Parallel::ForkManager来管理多个工作进程。Perl 解释器线程很混乱,最好避免使用。)