hi

i'm looking for a way to improve a program by using threads. i have no
experiece at all with threads so thought i might ask this list.

i have got an array of dynamic size. while "foreaching" inside this
array there will be a call to a subroutine [which again will call
other subs].

so my thought was that maybe when one thread might get starting with
element[0] and thus cascade into several subs, another thread might
begin with element[1] and so on.

1) is that possible/wise ?
2) if yes, how ?

i have started  a _naive_ and simplified example below that somewhat 
should illustrate what i'm trying to achieve:
  loop an array. 
  create a thread for each element -> calling the sub.
  let sub fill a hash
  print the hash


any pointers [apart from the man page] much appriciated

thanks
../allan



---------


use strict;
use threads;
use threads::shared;

my @array : shared = qw (a b c d a b f g);
my %cache : shared;

# array loop
for (my $i = 0; $i < $#array; $i++) {
  my $element = $array[$i];
  my $thr1 = threads->new(\&fill_cache, $element);
  $thr1->detach;
}

foreach my $key (sort keys %cache) {
  print "$key => $cache{$key}\n";
}

sub fill_cache {
  my $element = shift;
  # do some processing that might take up to 30 seconds
  if (exists($cache{$element})) {
    $cache{$element} += 1;
  } else {
    $cache{$element} = 1;
  }
}
__END__

Reply via email to