Perl - Threads

From Torben's Wiki
Jump to: navigation, search

Parallel computation using multiple threads for usage of multiple cpu cores. From [1]

use strict; use warnings;
use threads;
use Thread::Queue;

my $numThreads = 2;

# list of jobs
my $q = new Thread::Queue;
$q->enqueue($_) for 1..1000;
for (1..$numThreads) { $q->enqueue(undef); } # for stop condition

my @Threads = ();

for my $thrNum (1..$numThreads) { 
  push @Threads,threads->new(\&tsub,$thrNum);
}

# Wait for all threads to complete execution.
foreach (@Threads) {
  print $_->join; # wait for thread, returns return value
}
 
# the work to be done for all items of queue
sub tsub {
  my $thrNum = shift;
  my $howMany=0;

  while (my $x = $q->dequeue) {
    # process $x
    my $sum=0;
    while ($sum<$x) {
      $sum+=0.01;
    }
    
    print "$thrNum: $x\n";    
    $howMany++;
  }
  return "$thrNum: $howMany computed\n";
}


Sharing variables

use threads::shared;
my $count :shared ;
...
sub threadSub{
  lock ($count); #until end of block
  $count ++;  # test
}
Personal tools