Tuesday, December 23, 2008

Parallel Programming with Perl

Perl have a great support for parallel execution since version 5.6. Shared variables guarantees you to modify the state at the same time from different threads, without the internal state of the variable will become corrupted.

#!/usr/bin/perl
use strict;
use threads;
use threads::shared;

$|=1; # autoflush on

my $running = 1;
share $running;

print "Press enter to stop\n";

my $job = async {
  while($running > 0) {
    print ".";
    sleep 1;
  }
};

my $enter= <STDIN>;
$running = 0;
$job->join();