为什么我的 ActivePerl 程序报告“抱歉。”线程用完了?
Tom Christiansen 的示例代码(类似于 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),然后以“抱歉”终止。线程不足
'警告。
在试图弄清楚为什么我可以创建的线程数量受到限制时,我将 usethreads;
行替换为 usethreads (stack_size => 1);
。最终的代码可以愉快地处理 2000 多个线程。
谁能解释这种行为?
Tom Christiansen's example code (à la perlthrtut) is a recursive, threaded implementation of finding and printing all prime numbers between 3 and 1000.
Below is a mildly adapted version of the script
#!/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);
When run on my machine (under ActiveState & Win32), the code was capable of spawning only 118 threads (last prime number found: 653) before terminating with a 'Sorry. Ran out of threads
' warning.
In trying to figure out why I was limited to the number of threads I could create, I replaced the use threads;
line with use threads (stack_size => 1);
. The resultant code happily dealt with churning out 2000+ threads.
Can anyone explain this behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自 线程文档:
From the threads documentation: