> Mi goal is that each thread could process an element of an array that
> has 10 elements, so thread0 process array[0], thread1 process array[1]
> and so on until thread9 process array[9]
>
> Those 10 lines come from a file that Perl reads in chunks of ten lines
> until EOF
First of all, your code doesn't /do/ anything with the data you pass
it in proceso...
I'm curious, why 10 lines at a time? And honestly, you probably don't
need threads for this...
my $group_size = 10;
my @accumulator = ();
while (<FILE>) {
chomp;
push @accumulator, $_;
next if $. % $group_size;
# do stuff with @accumulator
}
# do stuff with @accumulator (leftovers)
Some recommended reading on perl threads:
<http://www.perlmonks.org/index.pl?node_id=288022>
<http://www.perldoc.com/cgi-bin/htsearch?words=threads>
And here's some relatively generic threading code that should get you
started (if you still think you need to use threads):
--CODE--
#!/usr/bin/perl -w
use strict;
use threads;
use threads::shared;
our $group_size = 10;
our $num_threads = 3;
our @threads = ();
our @buffer : shared = ();
our $main_done : shared = 0;
sub process_buffer {
my $self = threads->self;
while(1) {
my @rows = ();
{ lock(@buffer);
if (not @buffer) {
if ($main_done) {
cond_broadcast(@buffer);
print STDERR 'thread '. $self->tid ." exiting\n";
return;
}
print STDERR 'thread '. $self->tid ." waiting on buffer\n";
cond_wait(@buffer);
}
next if not $main_done and @buffer < $group_size;
push(@rows, shift(@buffer))
while @buffer and @rows < $group_size;
}
next if not @rows;
print 'thread '. $self->tid .': '. join(', ', @rows) ."\n";
} # end infinite while
}
for my $i (1 .. $num_threads) {
print STDERR "starting thread $i\n";
unshift @threads, threads->create('process_buffer');
}
while (<DATA>) {
chomp;
next unless /^\w+/;
lock(@buffer);
# print STDERR "loading buffer up with [$_] on line $.\n";
push @buffer, $_;
cond_signal(@buffer) unless $. % $group_size;
}
{ lock($main_done);
print STDERR "main thread done\n";
$main_done = 1;
lock(@buffer);
cond_broadcast(@buffer);
}
for my $t (@threads) {
$t->join();
print STDERR 'joined thread '. $t->tid ."\n";
}
__DATA__
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>