首页 > 解决方案 > 你如何在 Perl 线程中使用数组引用?

问题描述

我想在线程中保留带有数组引用的哈希。我收到以下错误。

以下代码可以按原样执行。您将看到如下错误消息

./thread1.pl 第 25 行的共享标量值无效。

#!/usr/bin/env perl

use v5.18;
use strict;
use warnings;
use Data::Dumper;
use threads;
use threads::shared;

my %myhash :shared;
my $stop_myfunc :shared = 0;
my $count = 0;
my $listref;

my @a = ('1','2');

@$listref = @a;

%myhash = (
    rootdir => "<path>/junk/perl",
    listref => $listref,
);

sub my2ndfunc {
    print "I am in the thread\n";
    $count++;
    $myhash{$count} = 0;
}

sub myfunc {
    while ($stop_myfunc == 0) {
        sleep(1);
        my2ndfunc();
    }
}

my $my_thread = 0;
$stop_myfunc = 0;
$my_thread = threads->create('myfunc');

$myhash{'test'} = 0;
sleep(3);
print Dumper \%myhash;
$stop_myfunc = 1;
$my_thread->join();


1;

我尝试将数组 ref 声明为:shared,但没有帮助。

有什么我在这里想念的吗。我在这里想不出任何其他选择。任何帮助表示赞赏。

标签: multithreadingperl

解决方案


线程:共享

共享变量只能存储标量、共享变量的引用或共享数据的引用

您必须shared_clone使用任何其他数据类型。

my @a = ('1','2');
my $listref = shared_clone(\@a);

%myhash = (
    rootdir => "<path>/junk/perl",
    listref => $listref,
);

由于您可能不需要您共享的数据结构的原始副本,因此最好首先在shared_clone语句中定义它。

my %myhash :shared = (
    rootdir => "<path>/junk/perl",
    listref => shared_clone( ['1', '2'] ),
    inventory => shared_clone( { additional => [qw/pylons doritos mountain_dew/] ),
);


推荐阅读