in reply to [threads] Sharing object through threads
If you want to push a ref onto a shared array, you have to share that ref first:
#!/usr/bin/perl use strict; use threads; use threads::shared; use tmp; my $rf = tmp->new(); share(my @data); my @threads; for ( my $count = 1; $count <= 10; $count++) { my $t = threads->new(\&sub1, $count); push(@threads,$t); } foreach (@threads) { my $num = $_->join; print "done with $num -- @data\n"; } print "End of main program @data\n"; sub sub1 { my $num = shift; print "started thread $num\n"; print "done with thread $num\n"; push (@data,share( $rf )); #### NOTE CHANGE HERE! return $num; }
With that change, your code runs:
c:\test>807599.pl started thread 1 done with thread 1 started thread 2 done with thread 2 started thread 3 done with thread 3 started thread 4 done with thread 4 started thread 5 done with thread 5 started thread 6 done with thread 6 started thread 7 done with thread 7 started thread 8 done with thread 8 started thread 9 done with thread 9 started thread 10 done with 1 -- tmp=HASH(0xf4a08) tmp=HASH(0xf4a50) t done with thread 10 done with 2 -- tmp=HASH(0xf4a98) tmp=HASH(0xf4978) t done with 3 -- tmp=HASH(0xf4990) tmp=HASH(0xf4b40) t done with 4 -- tmp=HASH(0xf4b70) tmp=HASH(0xf4ba0) t done with 5 -- tmp=HASH(0xf4bb8) tmp=HASH(0xf4a68) t done with 6 -- tmp=HASH(0xf49d8) tmp=HASH(0xf4ae0) t done with 7 -- tmp=HASH(0xf4c18) tmp=HASH(0xf4b58) t done with 8 -- tmp=HASH(0xf49f0) tmp=HASH(0xf4a50) t done with 9 -- tmp=HASH(0xf4c48) tmp=HASH(0xf4978) t done with 10 -- tmp=HASH(0xf4c60) tmp=HASH(0xf4b40) End of main program tmp=HASH(0xf4c78) tmp=HASH(0xf4
Note: The ability to share blessed references is a relatively new feature of threads::shared. I have done very little with and I am dubious of its benefits, but it does appear to work!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: [threads] Sharing object through threads
by baxy77bax (Deacon) on Nov 17, 2009 at 12:57 UTC | |
by ikegami (Patriarch) on Nov 17, 2009 at 19:58 UTC | |
by BrowserUk (Patriarch) on Nov 17, 2009 at 20:46 UTC | |
by ikegami (Patriarch) on Nov 17, 2009 at 22:13 UTC | |
by BrowserUk (Patriarch) on Nov 17, 2009 at 22:22 UTC | |
| |
by BrowserUk (Patriarch) on Nov 17, 2009 at 19:27 UTC |