在Perl中使用共享哈希

时间:2015-06-01 22:31:57

标签: multithreading perl hash shared

为什么我会收到此错误?

  

线程1异常终止:thr_hash.pl第8行的共享标量值无效。

use threads;
use threads::shared;
use Data::Dumper;

my %h:shared;

threads->create(sub{
    $h{manager} = {
        name => 'John',
        surname => 'Doe',
        age => 27
    };
})->detach;

sleep 1;

print Dumper \%h;

1 个答案:

答案 0 :(得分:3)

在赋值中使用变量(本例中为匿名哈希)时使用shared_clone():

use threads;
use threads::shared;
use Data::Dumper;

my %h:shared;

threads->create(sub{
    $h{manager} = shared_clone({
        name => 'John',
        surname => 'Doe',
        age => 27
    });
})->detach;

sleep 1;

print Dumper \%h;

输出:

$VAR1 = {
          'manager' => {
                         'surname' => 'Doe',
                         'name' => 'John',
                         'age' => 27
                       } 
        };