Perl - Threads

From Torben's Wiki
Revision as of 09:57, 3 January 2018 by Torben (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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
}