看来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 );
}
最佳答案
线程的工作原理与进程非常相似-线程退出后,它作为“僵尸”线程停留在线程列表中,直到另一个线程(不一定是其父线程)调用$thr->join
来收集其返回值。
您不会在任何地方调用$thr->join
,因此这些线程正在堆积。您可以使用threads->list(threads::joinable)
来检查哪些线程已经退出并且现在可以加入。
(或者,考虑使用Parallel::ForkManager
管理多个工作进程。Perl解释器线程比较困惑,最好避免使用。)
关于multithreading - 基本的Perl线程: threads->list() does not decrease,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47760887/