在Perl中使用线程的哈希表

时间:2013-09-22 08:43:42

标签: perl

我编写了以下简短脚本,并继续收到错误:

Invalid value for shared scalar at E:\Scripts\Threads.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 = { “伦敦”, “NYC”};

更新了脚本:

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: $@";

    }
}

1 个答案:

答案 0 :(得分:3)

共享

@destinations,但{ }创建的哈希不是。使用

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

但正如sundar指出的那样,你可能首先不想要哈希。

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