代码之家  ›  专栏  ›  技术社区  ›  Zaid

为什么我的ActivePerl程序报告“对不起”。线程用完了?

  •  2
  • Zaid  · 技术社区  · 16 年前

    Tom Christiansen's example code (洛杉矶) perlthrtut

    #!/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&下);在以' Sorry. Ran out of threads “警告。

    use threads; 符合 use threads (stack_size => 1); . 生成的代码愉快地处理了大量的2000多个线程。

    有人能解释这种行为吗?

    1 回复  |  直到 16 年前
        1
  •  3
  •   weismat    16 年前

    从 threads documentation

    不同平台的默认每线程堆栈大小差别很大,几乎总是远远超过大多数应用程序所需的大小。在Win32上,Perl的makefile显式地将默认堆栈设置为16MB;在大多数其他平台上,使用系统默认值,这可能比需要的要大得多。
    通过调整堆栈大小以更准确地反映应用程序的需要,可以显著减少应用程序的内存使用,并增加同时运行的线程数。
    请注意,在Windows上,地址空间分配粒度为64 KB,因此,将堆栈设置为小于Win32 Perl上的堆栈将不会节省更多内存。