I am working on a project implemented in Perl and thought that it would be an idea to use threads to distribute work, because tasks can be performed independently of each other and only read from shared data in memory. However, performance is nowhere near as I expect. So after some research, I can only conclude that threads in Perl basically suck, but I keep wondering how performance goes down as soon as I implement one common variable.
For example, this small program has nothing in common and consumes 75% of the CPU (as expected):
use threads;
sub fib {
my ( $n ) = @_;
if ( $n < 2 ) {
return $n;
} else {
return fib( $n - 1 ) + fib( $n - 2 );
}
}
my $thr1 = threads->create( 'fib', 35 );
my $thr2 = threads->create( 'fib', 35 );
my $thr3 = threads->create( 'fib', 35 );
$thr1->join;
$thr2->join;
$thr3->join;
And as soon as I present the general variable $a, CPU utilization is somewhere between 40% and 50%:
use threads;
use threads::shared;
my $a : shared;
$a = 1000;
sub fib {
my ( $n ) = @_;
if ( $n < 2 ) {
return $n;
} else {
return $a + fib( $n - 1 ) + fib( $n - 2 );
}
}
my $thr1 = threads->create( 'fib', 35 );
my $thr2 = threads->create( 'fib', 35 );
my $thr3 = threads->create( 'fib', 35 );
$thr1->join;
$thr2->join;
$thr3->join;
, $a , . , .
Perl 5.10.1 Cygwin Windows XP. , , Windows, () Perl.