General Guidelines

Here are some general guidelines for lock usage. Note that these aren’t hard-and-fast rules, just things to keep in mind.

Avoid Recursing on Exclusive Locks

When an exclusive hold or lock is acquired, the holder usually assumes that it has exclusive access to the objects the lock protects. Unfortunately, recursive locks can break this assumption in some cases. As an example, suppose function F1 uses a recursive lock L to protect object O. If function F2 acquires L, modifies O, leaving it in an inconsistent state, and then calls F1, F1 will recursively acquire L and falsely assume that O is in a consistent state.[7]

One solution to this problem is to use a nonrecursive lock and to rewrite F1 so that it does not acquire L. Instead, L must be acquired before calling F1.

Avoid Holding Exclusive Locks for Long Periods of Time

Exclusive locks reduce concurrency and should be released as soon as possible. Note that it is better to hold a lock for a short period of time when it is not needed than to release the lock only to reacquire it (Baldwin, 2002). This is because the operations to acquire and release a lock are relatively expensive.



[7] This paragraph is adapted from Locking in the Multithreaded FreeBSD Kernel by John H. Baldwin (2002)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.253.152