windows - 为什么我的 ActivePerl 程序报告 'Sorry. Ran out of threads' ?

标签 windows perl multithreading activeperl

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

谁能解释一下这种行为吗?

最佳答案

来自threads documentation :

The default per-thread stack size for different platforms varies significantly, and is almost always far more than is needed for most applications. On Win32, Perl's makefile explicitly sets the default stack to 16 MB; on most other platforms, the system default is used, which again may be much larger than is needed.
By tuning the stack size to more accurately reflect your application's needs, you may significantly reduce your application's memory usage, and increase the number of simultaneously running threads.
Note that on Windows, address space allocation granularity is 64 KB, therefore, setting the stack smaller than that on Win32 Perl will not save any more memory.

关于windows - 为什么我的 ActivePerl 程序报告 'Sorry. Ran out of threads' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2442436/

相关文章:

perl - 向@INC 添加路径但不在 Perl 脚本中

c++ - 在后台运行 "While loop"

windows exe 到 linux exe

perl - 在 Perl 中从 pdf 读取文本时遇到问题

c - SSE 内部函数 : Fastest way to test for all 0s or 1s?

mysql - 数据库中的运动跟踪

android - 异步 Pubnub 调用阻塞 android ui 线程

java - Jersey 的多线程

c# - 在 MonoGame 中获取窗口坐标

windows - 命名空间扩展中用于删除操作的入口点是什么?