2016-11-25 113 views
-1
foreach $thr (1..5) 
    {        
    $threads[$thr]=threads->create("worker");   
    }  

是這兩個代碼不同

foreach (1..5) 
    {        
    push @threads,threads->create("worker");   
    } 

後效果很好,還有前給出警告。

#!/usr/bin/perl          
use strict;           
use threads;           
use threads::shared;         
use Thread::Queue;         

my $queue = Thread::Queue->new();     
my @threads; 
my $thr; 
#----------------------------------------create         
#send work first,and then creat threads, the first thread work earlier. 
$queue->enqueue(1..10000); 
foreach (1..5) 
    {        
    push @threads,threads->create("worker");   
    }             

$queue->end();      

sub worker 
    {           
    while (my @DataElement = $queue->dequeue(100)) 
     { 
     my $tid = threads->tid();  
     #open (my $out,">>$tid.txt") or die $!; 
     print "Threads ID:$tid\[email protected]\n";   
     #print $out "Threads ID:$tid\[email protected]\n"; 
     #close $out;  
     }            
    }   

#----------------------------------------cut  
my $thr_num=1;          
my $i; 
while ($thr_num) 
    { 
    $i++;           
    foreach (@threads) #store threads, TRUE even if joined. 
     {        
     $thr_num = threads->list();     
     print "threads total: $thr_num\n";    
     if ($_->is_running()) 
      {      
      sleep 1; #wait        
      next;         
      }                        
     if ($_->is_joinable()) 
      {      
      $_->join();        
      }                         
     sleep 1;# wait      
     } 
    print $i,"\n";            
    } 

這是整個代碼。並且警告是無法在線程隊列2(1).plx.line42上的未定義值上調用方法「is_running」。 Perl用活動線程退出。

+0

你能否分享一下你所得到的警告? – AbhiNickz

+0

我已發佈代碼和警告。 – c11cc

+4

Perl數組從'0'開始,所以也許你想做'0..4'而不是'1..5',看看你的警告是否消失。 – xxfelixxx

回答

3

不會,你會得到不同的數據結構。正如你可以從這個簡化版本的代碼中看到的。

#!/usr/bin/perl 

use strict; 
use warnings; 
use 5.010; 

use Data::Dumper; 

my @threads; 

foreach my $thr (1 .. 5) { 
    $threads[$thr] = 'A Thread'; 
} 

say Dumper \@threads; 

@threads =(); 

foreach (1 .. 5) { 
    push @threads, 'A Thread'; 
} 

say Dumper \@threads; 

的輸出是:

$VAR1 = [ 
      undef, 
      'A Thread', 
      'A Thread', 
      'A Thread', 
      'A Thread', 
      'A Thread' 
     ]; 

$VAR1 = [ 
      'A Thread', 
      'A Thread', 
      'A Thread', 
      'A Thread', 
      'A Thread' 
     ]; 

在第一個例子中,在開始填充在元件1的陣列,所以第一個元件(其具有索引0)包含undef

+0

是的,這是問題所在。 – c11cc

相關問題