【发布时间】:2021-03-06 15:12:11
【问题描述】:
大家好~ 我用 Perl 编写了一个非常简单的代码,使用多线程。代码如下。
#!/bin/perl
use strict;
use threads;
use Benchmark qw(:hireswallclock);
my $starttime;
my $finishtime;
my $timespent;
my $num_of_threads = 1;
my $total_size = 10000000;
my $chunk_size = int($total_size / $num_of_threads);
if($total_size % $num_of_threads){
$chunk_size++;
}
my @threads = ();
$starttime = Benchmark->new;
for(my $i = 0; $i < $num_of_threads; $i++) {
my $thread = threads->new(\&search);
push (@threads, $thread);
}
foreach my $thread (@threads) {
$thread->join();
}
my $finishtime = Benchmark->new;
$timespent = timediff($finishtime, $starttime);
print "$num_of_threads threads used in ".timestr($timespent)."\nDone!\n";
sub search{
my $i = 0;
while($i < $chunk_size){
$i++;
}
return 1;
}
这段代码运行良好,当增加线程数时,它会运行得更快。
但是,当在中间添加额外的行时,会创建一个很大的数组,添加更多线程时代码会运行得更慢。带有附加行的代码如下所示。
#!/bin/perl
use strict;
use threads;
use Benchmark qw(:hireswallclock);
my $starttime;
my $finishtime;
my $timespent;
my $num_of_threads = 1;
my $total_size = 10000000;
my $chunk_size = int($total_size / $num_of_threads);
if($total_size % $num_of_threads){
$chunk_size++;
}
##########Additional codes##########
print "Preparing data...\n";
$starttime = Benchmark->new;
my @array = ();
for(my $i = 0; $i < $total_size; $i++){
my $rn = rand();
push(@array, $rn);
}
$finishtime = Benchmark->new;
$timespent = timediff($finishtime, $starttime);
print "Used ".timestr($timespent)."\n";
######################################
my @threads = ();
$starttime = Benchmark->new;
for(my $i = 0; $i < $num_of_threads; $i++) {
my $thread = threads->new(\&search);
push (@threads, $thread);
}
foreach my $thread (@threads) {
$thread->join();
}
my $finishtime = Benchmark->new;
$timespent = timediff($finishtime, $starttime);
print "$num_of_threads threads used in ".timestr($timespent)."\nDone!\n";
sub search{
my $i = 0;
while($i < $chunk_size){
$i++;
}
return 1;
}
我对 Perl 的多线程中的这种行为感到非常困惑。有谁知道这里可能出了什么问题?
谢谢!
【问题讨论】:
-
我没有时间查看详细信息,但每个线程都会复制
@array(以及任何其他未声明为共享的变量),我猜这是缓慢的部分。使用threads::shared并将@array声明为:shared;这应该会提高性能。 -
谢谢@Dada!它确实适用于上面的代码。
标签: multithreading perl memory