2012-06-29 33 views

回答

6

它共享變量,但您訪問的是與共享的變量不同的變量。 (use strict;會告訴你在這種情況下有不同的變量,總是使用use strict; use warnings;)修正是使用單個變量。

my $s :shared = 22; 

sub test { 
    my $thread = threads->new(\&thrsub); 
    $thread->join(); 
    print $s; 
} 

sub thrsub { 
    $s = 33; 
} 

test; 
4

您誤解了threads::shared的功能。它不允許跨詞彙範圍訪問變量。如果您想thrsub影響$s,則在創建線程時必須傳遞對它的引用。

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

sub test { 
    my $s = 22; 
    my $s_ref = share $s; 
    my $thread = threads->new(\&thrsub, $s_ref); 

    $thread->join(); 
    print $s; 

} 

sub thrsub { 
    my $s_ref = shift; 
    $$s_ref = 33; 
    return; 
} 

test;