Tom Christiansen 的示例代码(à la perlthrtut ) 是一个递归的线程实现,用于查找和打印 3 到 1000 之间的所有素数。
以下是脚本的轻度改编版本
#!/usr/bin/perl
# adapted from prime-pthread, courtesy of Tom Christiansen
use strict;
use warnings;
use threads;
use Thread::Queue;
sub check_prime {
my ($upstream,$cur_prime) = @_;
my $child;
my $downstream = Thread::Queue->new;
while (my $num = $upstream->dequeue) {
next unless ($num % $cur_prime);
if ($child) {
$downstream->enqueue($num);
} else {
$child = threads->create(\&check_prime, $downstream, $num);
if ($child) {
print "This is thread ",$child->tid,". Found prime: $num\n";
} else {
warn "Sorry. Ran out of threads.\n";
last;
}
}
}
if ($child) {
$downstream->enqueue(undef);
$child->join;
}
}
my $stream = Thread::Queue->new(3..shift,undef);
check_prime($stream,2);
当在我的机器上运行时(在 ActiveState 和 Win32 下),代码只能产生 118 个线程(找到的最后一个素数:653),然后以“ Sorry. Ran out of threads
”警告终止。
在试图弄清楚为什么我受限于我可以创建的线程数时,我use threads;
用use threads (stack_size => 1);
. 生成的代码愉快地处理了 2000 多个线程。
谁能解释这种行为?