Tom Christiansen的示例代码 (àla perlthrtut )是一个recursion的线程实现,用于查找和打印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
Sorry. Ran out of threads
警告。
在试图找出为什么我被限制到我可以创build的线程数量时,我replace了use threads;
use threads (stack_size => 1);
。 由此产生的代码愉快地处理了2000多个线程。
任何人都可以解释此行为?
从线程文档 :
不同平台的默认每线程堆栈大小变化很大,几乎总是远远超过大多数应用程序所需的大小。 在Win32上,Perl的makefile显式地将默认堆栈设置为16 MB; 在大多数其他平台上,使用系统默认值,这又可能比需要的大得多。
通过调整堆栈大小以更准确地反映应用程序的需求,可以显着减少应用程序的内存使用量,并增加同时运行的线程数量。
请注意,在Windows上,地址空间分配粒度为64 KB,因此,将堆栈设置为小于Win32 Perl上的堆栈将不会保存更多的内存。