If you use a package variable, it will be shared by all instances of the class, with or without sharing. Instance variables, even shared instance variables, need to be embedded within the instance.
Try this and see how you get on:
package Counter; use strict; use threads; use threads::shared; sub new { my $proto = shift; my $class = ref($proto) || $proto; my $self = {}; my $counter :shared = shift; ## Local shared variable $self->{ counter } = \$counter; ## Store a reference to it in the +object bless($self,$class); return $self; } sub incCounter { my $self = shift; lock ${ $self->{ counter } }; ++${ $self->{ counter } }; } sub getCounter { my $self = shift; lock ${ $self->{ counter } }; ${ $self->{ counter } }; } 1
#! perl -slw use strict; use threads; use Counter; my $t1 = async{ my $c1 = Counter->new( 100 ); $c1->incCounter while $c1->getCounter < 10000; return $c1->getCounter; }; my $t2 = async{ my $c2 = Counter->new( 100 ); $c2->incCounter while $c2->getCounter < 30000; return $c2->getCounter; }; print $t1->join; print $t2->join; __END__ C:\test>junk54 10000 30000
In reply to Re: threads with shared variables across multiple instances of a module
by BrowserUk
in thread threads with shared variables across multiple instances of a module
by fert
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |