请帮我解决我在 2 个文件中使用共享哈希线程的问题
我的第一个文件“H.pl”包含定义的哈希(非常大,有很多级别):
#!usr/bin/perl
use strict;
use warnings;
our %h;
%h= (
"hd",
{
"0", {"type", "fix", "ln", "8", "descr", "P"},
"1", {"type", "hex", "ln", "2", "descr", "H"},
},
"hdr",
{
"0", {"type", "fix", "ln", "8", "descr", "E"},
},
);
第二个文件“V.pl”包含更改哈希的主要代码和线程:#!usr/bin/perl
use strict;
use warnings;
use threads;
use threads::shared;
use Data::Dumper;
use lib '.';
require 'H.pl';
our %h;
threads->create(sub{
print "befor change in threads \n";
print Dumper \%h;
$h{"hd"}{"0"}{"value"} = "hello";
$h{"hd"}{"0"}{"descr"} = "R";
$h{"hdr"}{"0"}{"value"} = "hello";
print "after change in threads \n";
print Dumper \%h;
}
);
sleep 1;
print "without threads \n";
print Dumper \%h;
我尝试使用 our %h:shared;
在这两个文件中,但总是得到错误 Invalid value for shared scalar at H.pl
我如何分享我的哈希?感谢帮助
最佳答案
根据文档:
Shared variables can only store scalars, refs of shared variables, or refs of shared data (discussed in next section):
如果要共享不浅的哈希,则需要先共享内部引用。
您可以使用
shared_clone
为此发挥作用。将以下行添加到 our %h
下面的 V.pl 中使程序工作:%h = %{ shared_clone(\%h) };
此外,存储 create
的结果到变量 $t
而不是 sleep
, 运行 $t->join
.通常最好使用更高级别的模块,如 Thread::Queue并且只在线程之间发送您实际需要的数据。
关于multithreading - 珀尔。 2 个文件中的共享哈希线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65027522/