my $x :shared;
$x = 0;
sub my_task {
my $id = shift;
for (1 .. 5) {
sleep 2*rand();
{ # lock scope
lock($x);
print "thread $id found $x\n";
$x = $id;
sleep 2*rand();
}
}
}
threads->create('my_task', $_) for 1 .. 3;
sleep 5 while threads->list(threads::running);
lock is lexically scoped. Delay outside the lock scope allows other threads a chance at changing $x.