From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of Pravin
Talegaonkar
Sent: 19 January 2006 11:36
To: [email protected]
Subject: Threads in Perl
> Dear Gurus,
>
> I need to use threads in Perl. I have following requirement. I need to
process few files at a given time, I
> used to use following approach
>
> 1) Get the names of all the files in Array
> 2) Process all the files one by one.
>
> This was a simple one, but it takes lot of time and hence I decided to
use threads. What I wanted was
> 1) Get the names of all the files in Array
> 2) Process 2 files at a given time.
> 3) In case any of the file finishes processing, immediately process
next file from the array. So that at any
> given instance, script should process 2 files (Of course excluding the
last instance).
I would suggest using a queue (Thread::Queue) rather than an array. For
example:
use strict;
use warnings;
use threads;
use Thread::Queue;
my @files = ('A'..'Z');
my $nthreads = shift || 3;
die "Thread count should be between 1 and 10\n"
unless $nthreads > 1 && $nthreads < 11;
my $file_queue = Thread::Queue->new;
# Populate the queue before starting the threads, because they will
# exit if the queue is empty.
$file_queue->enqueue(@files);
# Start threads
my @thread_list;
for (1..$nthreads) {
my $thr = threads->create(\&thread_sub, $file_queue)
or die "Failed to create thread: $!\n";
push @thread_list, $thr;
}
# Wait for threads to finish
foreach my $thr (@thread_list) {
$thr->join();
}
# Thread function. Process files until none left then exit.
sub thread_sub {
my $file_queue = shift;
my $thr = threads->tid();
while (my $filename = $file_queue->dequeue_nb()) {
print "Thread $thr processing file $filename\n";
sleep 1;
}
}
HTH
--
Brian Raven
=================================
Atos Euronext Market Solutions Disclaimer
=================================
The information contained in this e-mail is confidential and solely for the
intended addressee(s). Unauthorised reproduction, disclosure, modification,
and/or distribution of this email may be unlawful.
If you have received this email in error, please notify the sender immediately
and delete it from your system. The views expressed in this message do not
necessarily reflect those of Atos Euronext Market Solutions.
L'information contenue dans cet e-mail est confidentielle et uniquement
destinee a la (aux) personnes a laquelle (auxquelle(s)) elle est adressee.
Toute copie, publication ou diffusion de cet email est interdite. Si cet e-mail
vous parvient par erreur, nous vous prions de bien vouloir prevenir
l'expediteur immediatement et d'effacer le e-mail et annexes jointes de votre
systeme. Le contenu de ce message electronique ne represente pas necessairement
la position ou le point de vue d'Atos Euronext Market Solutions.
_______________________________________________
ActivePerl mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs