Hi, I'm having some issues making data sharing working. I have a program that creates a lot of data, and with all the passing around that it has to do, it runs out of memory really fast. So I looked into sharing the data between the threads, using a hash to put them in. However I can't seem to make it work.
I've made up a simple test program that illustrates my problem (below). Can
anyone show me what I need to do to make this work?
My actual program does a few things in better ways (like testing to see when
threads have finished), it's just the data sharing that I need some help
with.
It outputs:
% ./threadtest.pl
Thread: 0 + 0 = 0
Thread: 1 + 1 = 2
Thread: 2 + 2 = 4
Thread: 3 + 3 = 6
Thread: 4 + 4 = 8
Use of uninitialized value in concatenation (.) or string at ./threadtest.pl
line 26.
0 + 0 =
Use of uninitialized value in concatenation (.) or string at ./threadtest.pl
line 26.
1 + 1 =
Use of uninitialized value in concatenation (.) or string at ./threadtest.pl
line 26.
2 + 2 =
Use of uninitialized value in concatenation (.) or string at ./threadtest.pl
line 26.
3 + 3 =
Use of uninitialized value in concatenation (.) or string at ./threadtest.pl
line 26.
4 + 4 =
The program (annoted with line numbers):
#!/usr/bin/perl
use strict;
use warnings;
use threads;
use threads::shared; # Line 5
# Set up the initial data
my @data : shared;
for (my $i=0; $i<5; $i++) {
my %tempStruct : shared; # Line 10
$tempStruct{d1} = $i;
$tempStruct{d2} = $i;
push @data, \%tempStruct;
}
# Line 15
# Run the threads
for (my $i=0; $i<5; $i++) {
threads->new(\&run, $data[$i]);
}
# Line 20
# Wait for them all to finish
sleep(1);
# Display the results
for (my $i=0; $i<5; $i++) { # Line 25
print "$data[$i]{d1} + $data[$i]{d2} = $data[$i]{res}\n";
}
# Threaded sub: calculates the result and stores it in the hash it was
# passed # Line 30
sub run {
my %struct = %{ shift() };
$struct{res} = $struct{d1} + $struct{d2};
print "Thread: $struct{d1} + $struct{d2} = $struct{res}\n";
} # Line 35
Cheers,
--
Robin <[EMAIL PROTECTED]> JabberID: <[EMAIL PROTECTED]>
Hostes alienigeni me abduxerunt. Qui annus est?
PGP Key 0xA99CEB6D = 5957 6D23 8B16 EFAB FEF8 7175 14D3 6485 A99C EB6D
pgpbLBxI6QUHb.pgp
Description: PGP signature
