I am using multithread and want to push local time of each thread into array. I can print to localtime from thread successfully, but it wont push time into array. Printing array is not giving blank.
Please check.
My code:
#!/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);
}
You can use threads::shared
which enables you to share variables among threads,
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
}
Threads don't share variables. See threads::shared .
use threads;
use threads::shared;
my @arr :shared;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.