Voilà un exemple simple qui peut servir de base à un script multi threadé. Il calcule le hash md5 d'une liste de fichiers, ce qui est plutôt con, mais c'est à vous d'imaginer le traitement à effectuer.

Ce qui est intéressant, c'est :

  • le lancement des threads
  • les threads qui lockent le tableau, en enlèvent un élément, puis le libèrent
  • l'arrêt des threads
#!/usr/bin/perl
 
use strict;
use warnings;
use threads;
use threads::shared;
use Digest::MD5;
 
our $VERSION = 1.0;
our $SLASH = q{/};
 
# Getting command line arguments
my @arguments = @ARGV;
if (!$arguments[0])
{
    usage ();
}
my $directory = $arguments[0];
my $max_threads = 2;
if ($arguments[1] && $arguments[1] =~ /^\d{1,2}$/xms)
{
    $max_threads = $arguments[1];
}
 
# Getting regular files in the directory
my $DIR;
opendir $DIR , $directory or die "unable to opendir: $!\n";
my @files = grep { -f "$directory/$_" } readdir $DIR or die "unable to readdir: $!\n";
closedir $DIR or die "unable to closedir: $!\n";
my @tableau : shared = sort @files;
 
# Launching threads
my @threads;
for (1 .. $max_threads)
{
    my $thread = threads->create ('thread_code');
    push @threads , $thread;
}
 
# Waiting for the threads to finish
while (@threads)
{
    my $thread = shift @threads;
    $thread->join ();
}
print "fini\n" or die "unable to print: $!\n";
exit 0;
 
 
##################################
 
 
sub thread_code
{
    BOUCLE : while (1)
    {
	my $element;
	{
	    # In this block, we only manage the shared array
	    # We don't want it to be locked for too long
	    lock @tableau;
	    $element = shift @tableau;
	    if (!$element)
	    {
		last BOUCLE;
	    }
	    if ($element =~ /^\.{1,2}$/xms)
	    {
		next BOUCLE;
	    }
	}
 
	# We calculate the md5sum of the file, and we display it
	my $ctx = Digest::MD5->new;
	my $FILE;
	open $FILE , '<' , $directory.$SLASH.$element or next BOUCLE;
	$ctx->addfile ($FILE);
	close $FILE or next BOUCLE;
	my $digest = $ctx->hexdigest;
	print threads->self->tid () . " : $element -> $digest\n" or next BOUCLE;
    }
    return;
}
 
sub usage
{
    print <<"EOM" or die "unable to print: $!\n";
Usage: $0 directory [max_threads]
\tdirectory: the directory you want to scan.
\tmax_threads: the maximum number of threads you vant to run (1 .. 99). Defaults to 2.
EOM
    exit 1;
}
perl/exemple_de_fonky_script_multi_threade.txt · Last modified: 2010/01/12 13:29 (external edit)
www.chimeric.de Creative Commons License Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0