The reason for locking is to allow only 1 thread of control to manipulate a resource (or set of resources)at any given point in time. The mechanics are implementation specific.
Example... I have a Perl app that examines emails at my MTA. The examination takes longer than the interval between email arrivals, so I have multiple threads (each handling a single email). Think multiple checkout cashiers at a store, servicing one long customer line.
I have two counters:
This code example is of the mechanics of a single lock, there are many design patterns on how to us locks, when both updating and reading protected data. Imagine multiple threads updating the same linked list at the same time.
Perl locks are also "discretionary" (like seat belts) in that you can access those shared variable in other placed without locking the access if you want, your choice. But you might get an updated MsgCnt, with an old TotalBytes.# update shared counters use threads; use threads::shared; # needed for shared variables my $TotalsLock:shared; # variable to be the lock my $MsgCnt:shared; my $TotalBytes:shared; .... { lock $TotalsLock; # I have locked access $MsgCnt++; $TotalBytes += $bytesThisemail; } # lock released at end of enclosing scope
And to print out the results:
Hope this helps .....# update shared counters use threads; use threads::shared; # needed for shared variables my $TotalsLock:shared; # variable to be the lock my $MsgCnt:shared; my $TotalBytes:shared; .... { lock $TotalsLock; # I have locked access print "Activity Totals: $MsgCnt $TotalBytes]n"; } # lock released at end of enclosing scope
In reply to Re: Threading in perl - using Locks
by Wiggins
in thread Threading in perl - using Locks
by koti688
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |