multithreading - 你如何在 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
,但没有帮助。
有什么我在这里想念的吗。我在这里想不出任何其他选择。任何帮助表示赞赏。
解决方案
从线程:共享:
共享变量只能存储标量、共享变量的引用或共享数据的引用
您必须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/] ),
);
推荐阅读
- angularjs - DOM在angularjs中完成渲染后的样式表
- python - 使用 requests 和 Beautiful Soup 抓取时无法提取描述和评级
- c - C、乘法中的减号运算符
- clojure - 如何仅接受规范中的有序集合
- c# - 根据选择的列表框项仅加载一次 DataGridView
- python - 基于列在python中合并2个数据框
- iphone - 当 iPhone Xs,12.1 只有 eSIM 时,我如何获得 mobileCountryCode?
- android - NavigationDrawer 占据整个屏幕
- android - 更改动态加载按钮的颜色 onclick
- c# - 如何识别gridview中哪个项目中的元素