1
use threads;
use threads::shared;

sub test {
    my $s :shared = 22;
    my $thread = threads->new(\&thrsub);

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

}

sub thrsub {
    $s = 33;
}

test;

为什么线程中没有共享数据?

4

2 回答 2

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;
于 2012-06-29T18:00:24.997 回答
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;
于 2012-06-29T18:00:08.650 回答