in reply to Threading in perl - using Locks
My favorite analogy for locking is a lift in a building.
You have people (threads) moving around independantly on different floors (memory spaces) doing their alloted tasks. Occasionally, they need to share some information with collegues elsewhere and to do that they need to make use of a lift (shared resource). So, they move to the lift and press the button to signal their desire to use it.
If the lift is currently idle ( not signalled), then it responds immediately to their signal and the can move onto their destination (pretty much) immediately. If however, the lift is currently in use, they will have to wait for it to become free.
And there may already be several other people waiting (having signalled) for the lift, and which one will get serviced first is down to some permutation of their floor relative to the lift at the time they signalled; and at the time it becomes free; and who else is closer to the lift when it becomes free; and a bunch of other hueristics to do with scheduling (the OS dispatcher).
Of course there can be more than one lift (shared resource), and each lift can accomodate more than one person (shared arrays or hashes). And you can extend the analogy to deal with things like process inversions and deadlocks and similar. But, as analogies have a tendancy to do, the more you extend it, the more imperfect the it becomes. It's still a useful visualisation though.
The main thing to know about shared vars and locking in Perl, is that because variables have to be explicitly shared, the need for shared variables (and therefore locking, and the problems traditionally associated with it) is rare. For many applications, the user can avoid most, and even all need for explicit user sharing & locking by the juducious use of Thread::Queue.
And if you find yourself needing to employ widespread sharing and locking, then you are probably doing it wrong.
|
|---|