<snip>
> In general, increment on a shared variable is not safe. It's safe in
> the sense that Perl won't crash. It's _not_ save in the sense that
> you might miss increments. This is because shared variables in Perl
> are implemented as tied variables, i.e. with a FETCH and STORE. An
> increment is this basically a FETCH, an increment and a STORE. If
> second thread does a FETCH before the first one has done the STORE,
> you have lost 1 increment.
<<< I'm interested in this discussion because I'm sharing a hash across
threads (threads::shared) and it is getting updated quite frequently.
My current assumption is that for
$hash{$index}[$array_pos] += 1;
thread 1 could write to $hash{0}[0] at the same time thread 2 writes to
$hash{1}[0] without any chance of missing an update. Is it necessary to
lock %hash each time it is necessary to write to it?
Are these expressions handled differently?
1) $hash{$index}[$array_pos] += 1;
2) $hash{$index}[$array_pos]++;
Finally, when updating such a data structure are there efficiencies in
checking values (not committing to a write) prior to updating, eg.
$new_value = 1;
if ($hash{1}[1] == $new_value) {
print "Don't update for identical value!\n";
}
else
$hash{1}[1] = $new_value;
}
Best,
Moose