Locking guidelines

In this section, we will present a small but important set of heuristics or guidelines for the developer to keep in mind while designing and implementing multithreaded code that makes use of locks. These may or may not apply in a given situation; with experience, one learns to apply the right guidelines at the appropriate times.

Without further ado, here they are:

  • Keep locking granularity fine enough: lock data, not code.
  • Simplicity is key: Complex locking scenarios involving multiple locks and threads lead to not just performance issues (the extreme case being deadlock), but also to other defects. Keeping the design as simple as it can be is always good practice.
  • Prevent Starvation: Holding a lock for an arbitrarily ...

Get Hands-On System Programming with Linux now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.