Perl - Threads

From Torben's Wiki

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;

# Preparing Threads
my $q = new Thread::Queue;
my @Threads = ();

# the work to be done for all items of thread queue
sub tsub {
  my $thrNum = shift;
# processing query
  while (my $x = $q->dequeue) {
    $_ = "$pathToGnuplot $gpoutfile";
    say "Thread $thrNum: $x";
    system($x);  # $x = gnuplotfile
  }
  return;
}  

# Filling the queue with the list
$q->enqueue($_) for (@OutFiles);
for (1..$numThreads) { $q->enqueue(undef); } # for stop condition
# Fill the Threads Object
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
}

Sharing variables

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