gpt4 book ai didi

arrays - 无法从Perl中的子例程插入数组

转载 作者:行者123 更新时间:2023-12-03 13:14:17 26 4
gpt4 key购买 nike

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

请检查。

我的代码:

#!/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;

关于arrays - 无法从Perl中的子例程插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31398874/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com