无法从perl中的子例程推入数组

时间:2015-07-14 06:09:31

标签: arrays multithreading perl

我正在使用多线程,并希望将每个线程的本地时间推送到数组中。 我可以成功地从线程打印到本地时间,但它不会将时间推入数组。打印阵列没有空白。

请检查。

我的代码:

#!/usr/bin/Perl
use threads;
use WWW::Mechanize;
use LWP::UserAgent;

my @arr=();
my $num_of_threads = 2;
my @threads = initThreads();

foreach(@threads){
         $_ = threads->create(\&doOperation);
         }

foreach(@threads){
         $_->join();
         }

foreach(@arr){
         print "$_\n";
         }

sub initThreads{
            my @initThreads;
            for(my $i = 1;$i<=$num_of_threads;$i++){
                push(@initThreads,$i);
             }
            return @initThreads;
        }

sub doOperation{
        ##doing my main operation here
        my $a=localtime();
        print "$a\n";
        push(@arr,$a);
        }

2 个答案:

答案 0 :(得分:6)

您可以使用threads::shared来分享线程间的变量,

use threads;
use threads::shared;

my @arr :shared;
# ...

sub doOperation {

    my $a = localtime();
    print "$a\n";
    {
      lock(@arr);    # advisory exclusive lock for variable
      push(@arr,$a);
    }                # lock get released when going out of scope
}

答案 1 :(得分:4)

线程不共享变量。请参阅threads::shared

use threads;
use threads::shared;
my @arr :shared;