[英]Not able to push into array from subroutine in 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);
}
您可以使用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
}
线程不共享变量。 参见thread :: shared 。
use threads;
use threads::shared;
my @arr :shared;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.