Sharing object between threads - howto?
- From: Lejf Diecks <bastard_operator@xxxxxx>
- Date: Sat, 08 Sep 2007 13:47:14 +0200
Hi,
is it possible to share an object between the main program and a thread?
I wrote a class "SuperSnoop.pm" with the following constructor:
-- <snip> ---
package PlugIn::SuperSnoop;
sub new {
my $this = shift;
my $class = ref($this) || $this;
my $self = {};
bless $self, $class;
return $self;
}
-- <snip> ---
In the main program I create a new "SuperSnoop"-object and pass it to a thread:
-- <snip> ---
use threads;
sub startThread {
my ($obj) = @_;
print "Object inside thread: $obj\n";
}
my $obj = SuperSnoop->new();
print "Object outside thread (1): $obj\n";
my $thr = threads->create("startThread", $obj);
print "Object outside thread (2): $obj\n";
-- <snip> ---
Problem: It seems to me that "threads" creates a copy (!) of the object, because the reference changes INSIDE the thread:
-- <snip> ---
Object outside thread (1): PlugIn::SuperSnoop=HASH(0x10413d4c)
Object inside thread: PlugIn::SuperSnoop=HASH(0x106ea164)
Object outside thread (2): PlugIn::SuperSnoop=HASH(0x10413d4c)
-- <snip> ---
I tried "threads::shared" from CPAN, but it does'nt work for me. The perldoc for "threads::shared" points out:
"BUGS: bless is not supported on shared references. In the current version, bless will only bless the thread local reference and the blessing will not propagate to the other threads. This is expected to be implemented in a future version of Perl."
Is there a way to get it work anyway? I need only one instance of each object at runtime.
Regards,
Lejf
.
- Follow-Ups:
- Re: Sharing object between threads - howto?
- From: Mike Pomraning
- Re: Sharing object between threads - howto?
- From: zentara
- Re: Sharing object between threads - howto?
- Prev by Date: Re: Match repeating pattern
- Next by Date: FAQ 3.17 Is it safe to return a reference to local or lexical data?
- Previous by thread: FAQ 2.13 What mailing lists are there for Perl?
- Next by thread: Re: Sharing object between threads - howto?
- Index(es):