I will assume you have a handle on threads. Locking requires two concepts to be understood ... the reason for locks, and the mechanics of setting and clearing a lock
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: - Number of emails processed,
- Number of bytes processed.
which are updated by each of the threads at the end of processing an email.
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.
# 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
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.
And to print out the results: # 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
Hope this helps ..... |