perl does implicit locking of shared variables each time they are accessed, chiefly to avoid perl's internal data structures from getting corrupted. However, perl will not protect a variable across multiple accesses; for example, $i++ involves a read followed by a write. In between, another thread may have
modified the variable. The following code was run on a 4 CPU machine:
#!/usr/bin/perl -w
use threads;
use threads::shared;
my $i : shared = 0;
push @t, threads->new( sub { $i++ for 1..100_000 } ) for 1..4;
$_->join for @t;
print "i=$i\n";
$ perl588t /tmp/p
i=139728
Dave. | [reply] [d/l] |