如何将共享数据传递给Perl中的线程?

时间:2012-06-29 17:54:45

标签: multithreading perl

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;

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

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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;