multithreading - 珀尔。 2 个文件中的共享哈希线程

标签 multithreading perl hash shared

请帮我解决我在 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/

相关文章:

Perl - Facebook 图形 API

perl - 避免在命令行输入密码(sudo)

c++ - unordered_map 仅使用 16 个字符串来最大化唯一键

c++ - 哈希和模运算

Java应用线程创建

multithreading - 如何获取 GDB 中所有线程的回溯?

c# - 在 Windows 服务中异步运行外部进程

python - 是否可以从与创建进程的线程不同的线程等待子进程?

linux - Perl 脚本执行不断被终止 - 内存不足

perl - 在 Perl 中取消引用哈希值的哈希值