Hi,
Your code isn't running multiple threads. You create
a thread and then wait for it to finish with join()
before creating the next one. I altered this while
trying it out.
Why do you want threads in the first place? They are
pretty costly and it seems like you could possibly
have thousands of them. You might have to run this on
the monster box too :)
I added use strict and use warnings to your code, made
adjustments to get rid of warnings and it now runs fine.
See altered code below.
Have a look at perlthrtut, the threads manpage and
the threads::shared manpage.
hth,
#---------------------------------------------------
# Robert Friberg perl,java,xml,uml,sql,delphi,
# Systemutvecklare c/c++,vb,php,linux,apache
# 0733-839080
#
# Ensofus AB linuxservrar,serverhosting,
# www.ensofus.se internetsystem, Milj� Online
#---------------------------------------------------
#code starts
# I ALWAYS use these unless writing something very trivial
use warnings;
use strict;
use threads;
# All your variables were globals, particularly
# $localDir inside sub writeStat. All are now my variables instead.
my $currDir = `cd`;
#chomp only chops newlines
chomp($currDir);
opendir(IP_MAIN_DIR, $currDir);
#remove '.' and '..'
#why do this? Your next grep discards them anyways...
my @allBatchFolders = grep !/^\.\.?$/, readdir IP_MAIN_DIR;
#moved up, close ASAP
closedir(IP_MAIN_DIR);
@allBatchFolders = grep /^[a-z][a-z][a-z]$/, @allBatchFolders;
#open stat file for writing
open(STATFILE, ">$currDir\\stat.txt");
my @aThread;
# Start 1 thread per entry, not necessarily a directory. This is
# probably not what you wanted. And don't use indexing unless you must
foreach my $aDir (@allBatchFolders)
{
push @aThread, threads->new(\&writeStat, $aDir);
}
#wait for each thread to finish, discard returndata
foreach my $t (@aThread)
{
$t->join();
}
close(STATFILE);
sub writeStat
{
my $localDir = $currDir . "\\" . $_[0];
return unless -d $localDir;
local *DIRECTORY;
opendir(DIRECTORY, $localDir);
print "Start wile loop: $_[0]\n";
print STATFILE "Start wile loop: $_[0]\n";
rewinddir( DIRECTORY );
while (my $file = readdir(DIRECTORY))
{
writeToFile($_[0], $file);
}
print STATFILE "End wile loop: $_[0]\n";
print "End wile loop: $_[0]\n";
closedir(DIRECTORY);
}
sub writeToFile : locked
{
print STATFILE "Thread $_[0]: $_[1]\n";
print "Thread $_[0]: $_[1]\n";
}
#code ends