#!/usr/bin/perl #----------------------------------------------------- package p1; #----------------------------------------------------- use strict; use warnings; use threads; use threads::shared; sub new { my $class = shift; my $self = { @_ }; $self->{x2} = $self->{x1}; return bless $self, $class; } sub startThread { my $self = shift; my $thr; share ($self->{x2}); sub test { my $x1 = shift; my $r = int(rand()*1000); print "$x1: starting thread r=$r \$self{x1}=$self->{x1}\n"; sleep $r/100; print "$x1: setting variable\n"; $self->{x2} = $r; sleep 10; print "$x1: closing thread \$self{x2}=$self->{x2}\n"; threads->exit(); }; print "threads->create \$self{x1}=$self->{x1}\n"; $thr = threads->create('test', $self->{x1}); $thr->detach(); } #----------------------------------------------------- package main; #----------------------------------------------------- use strict; use warnings; my $objA = p1->new( x1 => 'A' ); my $objB = p1->new( x1 => 'B' ); my $objC = p1->new( x1 => 'C' ); print " $objA->{x1}=$objA->{x2} $objB->{x1}=$objB->{x2} $objC->{x1}=$objC->{x2}\n"; $objA->startThread(); $objB->startThread(); $objC->startThread(); for (my $i = 1; $i < 15; $i++) { print " $objA->{x1}=$objA->{x2} $objB->{x1}=$objB->{x2} $objC->{x1}=$objC->{x2}\n"; sleep 2; }