Why does my ActivePerl program report 'Sorry. Ran out of threads'?
Posted
by Zaid
on Stack Overflow
See other posts from Stack Overflow
or by Zaid
Published on 2010-03-14T14:21:19Z
Indexed on
2010/03/17
3:01 UTC
Read the original article
Hit count: 372
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?
© Stack Overflow or respective owner