The lock doesn't have to the be on the variable you are changing, so create a hash of mutexes.
my %h : shared; my %mutexes : shared; sub get_mutex { my ($k) = @_; my $mutex_ref = $mutexes{$k}; return $mutex_ref if $mutex_ref; lock($mutexes); my $new_mutex : shared; return $mutexes{$k} ||= \$new_mutex; } sub safe_set { my ($k, $v) = @_; lock ${ get_mutex($k) }; $h{$k} = $v; }
Update: Fixed error mentioned in reply.
In reply to Re: Avoid Locking Entire Hashes
by ikegami
in thread Avoid Locking Entire Hashes
by jagan_1234
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |