【问题标题】:Why does my ActivePerl program report 'Sorry. Ran out of threads'?为什么我的 ActivePerl 程序报告 'Sorry.跑出线程'?
【发布时间】:2011-01-27 09:33:51
【问题描述】:

Tom Christiansen's example code (à 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 多个线程。

谁能解释这种行为?

【问题讨论】:

    标签: windows perl multithreading activeperl


    【解决方案1】:

    来自threads documentation

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多