添加 Key/Value 到哈希(Perl)

Adding Key/Value To Hash(Perl)

您好,我正在尝试将多个 keys/values 添加到哈希中。基本上是文件名及其数据。 json 文件的每个内容都有散列和数组引用。包含文件名和数据的散列将在其他地方处理。

这是我的代码:

 sub getDecode {
    my $self = shift;
    my @arrUrls = ('http://domain.com/test.json', 'http://domain.com/test_two.json', 'http://domain.com/test3.json');

    my $resQueue = Thread::Queue->new();
    my $intThreads = 10;
    my @arrThreads = ();
    my %arrInfo = ();

    foreach my $strUrl (@arrUrls) {
          for (1..$intThreads) {
              push (@arrThreads, threads->create(sub {
                          while (my $resTask = $resQueue->dequeue) {
                                      my $resData = get($strUrl);
                                      my $strName = basename($strUrl, '.json');
                                      my $arrData = decode_json($resData);
                                      $arrInfo{$strName} = $arrData;
                          }
              }));
          }
   }

   $resQueue->enqueue(@arrUrls);
   $resQueue->enqueue(undef) for 1..$intThreads;
   $_->join for @arrThreads;

  return %arrInfo;       
  }

当我尝试在 %arrInfo 上转储数据时,没有给出任何输出。请帮忙!

你是多线程的,不共享变量。当一个线程产生时,现有的变量 -space 被克隆 - 所以每个线程都有它自己的 %arrInfo 的本地副本,它在退出时被丢弃。

您需要:

use threads::shared;
my %arrInfo : shared;

您还对线程生成循环做了一些奇怪的事情 - 您正在生成 10 个线程 x 3 个 URL - 对于 30 个线程,但只排队处理 3 个 URL。但是你实际上也根本没有使用 $resTask ,这没有多大意义。

所以我敢打赌你的代码最后会挂起,因为你正试图加入一些不完整的线程。

你可能会发现$resQueue -> end()比排队undef更合适。

使用共享哈希的示例:

use strict;
use warnings;
use threads;
use threads::shared;

use Data::Dumper;

my %test_hash : shared;
my %second_hash;

$test_hash{'from_parent'}       = 1;
$second_hash{'from_parent_too'} = 1;

threads->create(
    sub {
        $test_hash{'from_first'}       = 2;
        $second_hash{'from_first_too'} = 2;
    }
);
threads->create(
    sub {
        $test_hash{'from_second'}       = 3;
        $second_hash{'from_second_too'} = 3;
    }
);

foreach my $thr ( threads->list() ) { $thr->join }

print Dumper \%test_hash;
print Dumper \%second_hash;

对于 'worker threads' 风格的方法,我建议:Perl daemonize with child daemons