in reply to Passing objects between threads...any solutions ?
How brave are you?
The code below uses a technique I've been playing with to share two instances of an object between 10 threads that each modify whichever instance they get 100 times before terminating. The main thread then displays the values which will be whatever values were last set into them by whichever thread accessed them last. The program runs reliably under 5.8.4 on my (single cpu) system with no idication of errors, traps or memory leakage.
#! perl -slw use strict; use threads; use threads::shared; package Dummy; sub new { my $sem : shared; my $this : shared = 12345; my $that : shared = 'fred'; my $theOther : shared = 3.141592653; return bless { sem => \$sem, this => \$this, that => \$that, theOther => \$theOther, }, $_[ 0 ]; } sub this : lvalue { my $self = shift; lock ${ $self->{ sem } }; ${ $self->{ this } }; } sub that : lvalue { my $self = shift; lock ${ $self->{ sem } }; ${ $self->{ that } }; } sub theOther : lvalue { my $self = shift; lock ${ $self->{ sem } }; ${ $self->{ theOther } }; } sub combo { my $self = shift; lock ${ $self->{ sem } }; ${ $self->{ that } } = "[ ${ $self->{ this } } : ${ $self->{ theOt +her } } ]"; } package main; sub thread { Win32::Sleep rand( 1000 ); my( $obj ) = @_; bless $obj, 'Dummy'; for ( 1 .. 100 ) { Win32::Sleep rand( 1000 ); print threads->tid, ': ', join ' : ', $obj->this, $obj->that, + $obj->theOther; $obj->this = threads->tid; $obj->that = '' . threads->tid; $obj->theOther = rand 1000; $obj->combo; print threads->tid, ': ', join ' : ', $obj->this, $obj->that, + $obj->theOther; } } my @objs = map{ new Dummy } 1 .. 2; my @threads = map{ threads->create( \&thread, $objs[ rand 2 ] ) } 1 .. + 10; $_->join for @threads; bless $_, 'Dummy' for @objs; print 'Back in main: ', join ' :', $_->this, $_->that, $_->theOther for @objs;
The basis of idea is that
I haven't had the facilities to test this on a multi-processor system, but I think it should be safe. Any feedback you can let me have would be much appreciated.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Passing objects between threads...any solutions? (shared objects)
by kimanaw (Beadle) on Jun 10, 2005 at 03:32 UTC | |
by BrowserUk (Patriarch) on Jun 10, 2005 at 03:51 UTC | |
by kimanaw (Beadle) on Jun 10, 2005 at 21:27 UTC | |
by BrowserUk (Patriarch) on Jun 10, 2005 at 21:35 UTC |