I'm trying to find out when to lock a shared variable or not.
For scalars, it seems obvious: only when you want to modify it. It seems that there is no problem with concurrent read access to the same scalar, right?
Then, if you have one write and multiple reads to a single scalar, it seems you do not need locking either. Each read either gets the value before the write, or the one after, but not something else. Correct?
So, it seems you only need locking when you may have multiple concurrent write operations.
But what about hashes? Is it also true?
Are all the read operations below safe without locking?
my %h : shared; $x = $h{foo}; # R1 safe? @x = keys(%h); # R2 safe? while (($k, $v) = each(%h)) { ... } # R3 safe?
Then, is it ok, like for scalars, to have multiple reads and only one write without locking? Here are the write operations I have in mind:
$h{foo} = "change the existing 'foo' entry"; # W1 aka modification $h{bar} = "add a 'bar' entry"; # W2 aka insertion delete($h{zoi}); # W3 aka deletion
For R1, I hope that locking is not needed: you either get the value before the modification/insertion/deletion or the one after. Could you please confirm?.
Will R2 work while the hash is being modified? Of course, by the time you use the keys, the hash could have changed but if you simply access the hash with R1, there should be no problem: you may miss some keys or access non existing entries.
For R3, will it work at all?
Thanks in advance for your wisdom...
In reply to threads::shared - when to lock a hash ? by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |