in reply to share array of hashes between main program and thread
Try it this way:
#!/usr/bin/perl -w use warnings; use strict; use threads; use threads::shared; my @Array : shared = (); my $thr = threads->create( \&handle_array , \@Array ); while( 1 ) { do_something(\@Array); printf "Main: Number of files: ". scalar(@Array) . "\n"; sleep 5; } sub do_something { my ( $Array_ref ) = shift; my %hash : shared = ( file => 'test1.zip', price => '10.00', desc => 'the 1st test' ); push @{ $Array_ref } , \%hash; } sub handle_array { my ( $Array_ref ) = shift; while (1) { printf STDOUT "Thread: Number of elements before: %d\n", scalar @{ $Array_ref }; my %hash :shared = ( file => 'test1.zip', price => '10.00', desc => 'the 1st test' ); push( @{$Array_ref} , \%hash ); printf STDOUT "Thread: Number of elements after: %d\n", scalar @{ $Array_ref }; sleep 10; } }
The main point is that any structures (references) you push into a shared array, have also to be shared themselves.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: share array of hashes between main program and thread
by Adler (Novice) on Nov 11, 2009 at 07:39 UTC | |
by BrowserUk (Patriarch) on Nov 11, 2009 at 07:51 UTC | |
by Adler (Novice) on Nov 11, 2009 at 11:54 UTC | |
by BrowserUk (Patriarch) on Nov 11, 2009 at 12:01 UTC |