2010-03-14 34 views
2

Tom Christiansen's example code(點菜perlthrtut)是3和1000之間爲什麼我的ActivePerl程序報告'抱歉。跑出線程'?

下面查找和打印所有質數的遞歸,線程實現是稿件的溫和改編版本

#!/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下),該代碼只能在產生'Sorry. Ran out of threads'警告之前產生118個線程(發現最後一個素數:653)。

在試圖找出爲什麼我被限制爲可以創建的線程數時,我用use threads (stack_size => 1);替換了use threads;行。由此產生的代碼愉快地處理了2000多個線程。

任何人都可以解釋這種行爲嗎?

回答

3

threads documentation

默認每個線程堆棧大小爲不同的平臺顯著變化,並且幾乎總是遠遠超過需要的大多數應用。在Win32上,Perl的makefile顯式地將默認堆棧設置爲16 MB;在大多數其他平臺上,使用系統默認值,這又可能比需要的大得多。
通過調整堆棧大小以更準確地反映應用程序的需求,可以顯着減少應用程序的內存使用量,並增加同時運行的線程數。
請注意,在Windows上,地址空間分配粒度爲64 KB,因此,將堆棧設置爲小於Win32 Perl上的堆棧將不會保存更多內存。

+0

這很有趣。使用'$ child-> get_stack_size;'我得到'8096'。我假設這是以字節爲單位的,對吧? – Zaid 2010-03-14 16:31:08

+0

Windows文檔(http://msdn.microsoft.com/zh-cn/library/ms686774%28VS.85%29.aspx)提及64 kByte作爲一個典型的大小, 找到您需要調用的實際大小GetSystemInfo。這甚至可能是CPU體系結構依賴。 – weismat 2010-03-14 17:31:40

+0

此鏈接(http://www.perlmonks.org/?node_id=31432)可能會幫助您從perl獲取數據。 – weismat 2010-03-14 17:33:14

相關問題