fert has asked for the wisdom of the Perl Monks concerning the following question:
This one feels like I am abusing Perl's OO concepts in ways they were never meant to be used, but let's see if anybody has any ideas/experience.
I have a module which has some variables that need to be shared amongst threads it spawns.
my $var : shared = 0;
Which works fine for until you declare a second instance of the module. Then it seems like the namespace of the variable is shared with all other instances of this module, and each instance is sharing the variable.
I can see the uses of this, however what I need is a way to narrow the scope of the sharing of the variable to the instance in question.
Here is some simple sample code that replicates this:
package Counter; use strict; use threads; use threads::shared; my $counter : shared = 0; sub new { my $proto = shift; my $class = ref($proto) || $proto; my $self = {}; lock $counter; $counter = shift; bless($self,$class); return $self; } sub incCounter { lock $counter; $counter++; } sub getCounter { return $counter; } 1;
and
#!/usr/bin/perl -w use Counter; my $x = new Counter( 1 ); my $y = new Counter( 10 ); print $x->getCounter()."\n"; print $y->getCounter()."\n"; print "-------------\n"; $x->incCounter(); print $x->getCounter()."\n"; print $y->getCounter()."\n";
I've been playing with sharing a hash, and then somehow generating a unique name for each instance, to guarantee independence of these variables, but that seems a bit...nasty.
So can perl do this? Can I have multiple instances of a module with shared variables that are only shared among the child threads of each instance? Again I realize Thread::Pool must be thread safe across multiple instances, so there has to be a way, I think its just a question of how nasty the solution is..
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: threads with shared variables across multiple instances of a module
by BrowserUk (Patriarch) on Mar 25, 2010 at 17:47 UTC | |
by fert (Acolyte) on Mar 25, 2010 at 18:19 UTC | |
by BrowserUk (Patriarch) on Mar 25, 2010 at 19:56 UTC | |
by zerg13new (Initiate) on Mar 26, 2010 at 07:40 UTC | |
by BrowserUk (Patriarch) on Mar 26, 2010 at 16:19 UTC | |
by zerg13new (Initiate) on Mar 27, 2010 at 07:52 UTC | |
by BrowserUk (Patriarch) on Mar 27, 2010 at 17:01 UTC | |
|