http://qs321.pair.com?node_id=579585


in reply to Threads: why locking is required when using shared variables

This is a great introduction and, certainly, locking of shared variables is essential learning and understanding for anyone who is going to be using threads.

Perhaps it is worth mentioning, in this particular case, that the lock function doesn't need an explicit unlock. Rather, a locked variable becomes unlocked when the code execution exits the current scope.

Replies are listed 'Best First'.
Re^2: Threads: why locking is required when using shared variables
by ikegami (Patriarch) on Oct 20, 2006 at 17:17 UTC

    That reminds me of a very useful bit of information reguarding locking. A single lock variable can be used to control access to multiple shared variables. For example,

    my $list_head : shared; # Access controlled by $list_head. my $list_tail : shared; # Access controlled by $list_head. sub ... { ... { lock($list_head); ... code that uses $list_head and/or $list_tail ... } ... }

    It doesn't matter which variable is used as to control access to a give shared variable, as long as you *always* use the same lock variable to control access to that shared variable.