2

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 多个线程。

谁能解释这种行为?

4

1 回答 1

3

线程文档

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

于 2010-03-14T15:28:50.870 回答