2016-08-12 57 views
0

這是我的代碼。錯誤代碼爲'線程1異常終止:共享標量的值無效'

該代碼有一些關於散列共享的問題。

use strict; 
use warnings; 
use threads; 
use threads::shared; 

my %db; 
share(%db); 
my @threads; 

sub test{ 
    my $db_ref = $_[0]; 
    my @arr = ('a','b'); 
    push @{$db_ref->{'key'}}, \@arr; 
} 

foreach(1..2){ 
    my $t = threads->new(
     sub { 
      test(\%db); 
     } 
    ); 
    push(@threads,$t); 
} 

foreach (@threads) { 
    $_->join; 
} 

錯誤代碼。

Thread 1 terminated abnormally: Invalid value for shared scalar at test1.pl line 13. 
Thread 2 terminated abnormally: Invalid value for shared scalar at test1.pl line 13. 

我waana使用線程::共享。

但我不知道什麼是問題。

help me plz〜

回答

1

您只能將對共享對象的引用放入共享變量中。 @arr不是共享的,也不是您推送對@arr的引用的陣列。

更換

my @arr = ('a','b'); 
push @{$db_ref->{'key'}}, \@arr; 

my @arr :shared = ('a','b'); 

lock %$db_ref; 

# We can't use autovivification as we need a shared array. 
$db_ref->{'key'} = shared_clone([]); 

push @{$db_ref->{'key'}}, \@arr; 
0

我改變了代碼。 但不能保存散列(%db)中的所有數據。下一個代碼是校驗碼。

use strict; 
use warnings; 
use threads; 
use threads::shared; 

my %db; 
share(%db); 
my @threads; 

sub test{ 
    my $db_ref = $_[0]; 
    my @arr :shared = ('a','b'); 
    lock %$db_ref; 
    $db_ref->{'key'} = shared_clone([]); 
    push @{$db_ref->{'key'}}, \@arr; 
} 

foreach(1..5){ 
    my $t = threads->new(
     sub { 
      test(\%db); 
     } 
    ); 
    push(@threads,$t); 
} 

foreach (@threads) { 
    $_->join; 
} 

while(my ($key, $val) = each %db){ 
    print "$key => $val\n"; 
    foreach my $value (@$val) { 
     foreach (@$value) { 
      print $_, " "; 
     } 
     print "\n"; 
    } 
} 

%db中只有一個數據(a,b)。 我們必須在%db中增加一個數據。

相關問題