Perl 中带有线程的哈希表



我写了以下简短的脚本,但不断收到错误:

Invalid value for shared scalar at E:ScriptsThreads.pl line 19.

我不知道为什么,因为我在共享数组中使用共享值。

use strict;
use threads;
use threads::shared;
my $totalInstances = 0;
my $totalDest = 0;
my $totalResults = 0;
my @threads = threads->self();
my @resultsHash : shared = ();
my $dest : shared = ();
my $hostname : shared = ();
my @destinations : shared = ();
my @hostnames : shared = ();
@destinations={"London","NYC"};
@hostnames={"wev1010","web1111"};


foreach $dest (@destinations) {
    foreach $hostname (@hostnames) {
    push @threads, threads->new(&ParsingResponse,$hostname,$dest);
    }
    sleep(6);
}
foreach (@threads) {
    my $retval = eval ($_->join());
    if ($@) {
    print ERRFILE "Thread failed: $@";
    }
 }
###########################################
# Parsing response 
#  
###########################################
sub ParsingResponse
{
    push @resultsHash, {            
    dest => "$dest",
    hostname => "$hostname",
    }
}

我的代码中的第 19 行是:@destinations={"伦敦","纽约"};

更新的脚本:

use strict;
use threads;
use threads::shared;
our @threads = threads->self();
our %resultsHash : shared = ();
our $dest : shared = ();
our $hostname : shared = ();
our @destinations : shared = ();
our @hostnames : shared = ();
@destinations[0]="London";
@destinations[1]="Paris";
@hostnames[0]="wev1010";
@hostnames[1]="web1111";
sub ParsingResponse
{
$resultsHash{$dest}= "$hostname";
}

foreach $dest (@destinations) {
        foreach $hostname (@hostnames) {
    push @threads, threads->new(&ParsingResponse,$hostname,$dest);
        }     
}

foreach (@threads) {
        my $retval = eval ($_->join());
        if ($@) {
                print "Thread failed: $@";
    }
}
@destinations

共享的,但{ }创建的哈希不是。用

@destinations = share({"London","NYC"});

但正如 sundar 指出的那样,你可能一开始就不想要哈希。

@destinations = ("London", "NYC");

最新更新