async { lock $LockVar; $LockVar = 'Haha'; sleep 3; print "Thread 1: $LockVar\n" }; async { lock $LockVar; $LockVar = 'Hehe'; sleep 3; print "Thread 2: $LockVar\n" }; #### #!perl -w use strict; use 5.010; use threads; use threads::shared; my $LockVar :shared; $LockVar = 'default'; async { lock $LockVar; my $oldLockVar= $LockVar; $LockVar = 'Haha'; sleep 3; say "Thread 1: set var from $oldLockVar to $LockVar" }; async { lock $LockVar; my $oldLockVar= $LockVar; $LockVar = 'Hehe'; sleep 5; say "Thread 2: set var from $oldLockVar to $LockVar" }; my $TryToReadLockVar = threads->new( {'void' => 'void'}, sub { my $count = 1; while( 1 ) { say "try to modify the Lock var {$count} time"; $count += 1; lock($LockVar); # !!! say "Now setting LockVar"; $LockVar = 'this lock var has been change'; last; } }, ); $TryToReadLockVar->join(); say "LockVar is now $LockVar"; __END__ try to modify the Lock var {1} time Thread 1: set var from default to Haha Thread 2: set var from Haha to Hehe Now setting LockVar LockVar is now this lock var has been change Perl exited with active threads: 0 running and unjoined 2 finished and unjoined 0 running and detached