Course contentsShow
← Computer Science
Lesson 1286 of 2,87230. Process SynchronizationFree lesson

Lock Granularity and Performance

Balancing coarse-grained locks (simple, low concurrency) versus fine-grained locks (complex, high concurrency).

Lock Granularity and Performance

You'll learn how choosing the right "size" of lock—coarse-grained or fine-grained—dramatically affects both simplicity and concurrency in multithreaded programs.

What is Lock Granularity?

Lock granularity refers to how much data or code a single lock protects. Think of it like choosing between one big lock for an entire house versus separate locks for each room.

Coarse-grained locks protect large sections of data or code with a single mutex. For example, one lock might guard an entire database or data structure.

Fine-grained locks protect smaller, more specific pieces. You might use separate locks for different fields of a structure, different rows of a table, or different nodes in a linked list.

The Trade-Off

Coarse-grained locking is simple to implement and reason about—just acquire one lock, do your work, release it. However, it creates a bottleneck: only one thread can access the entire protected region at a time, even if threads want to work on completely independent data. Low concurrency, but simple code.

Fine-grained locking allows much higher concurrency—multiple threads can work simultaneously on different parts of the data structure. But it's complex: you must carefully track which locks protect what, acquire multiple locks in consistent order (to avoid deadlock), and handle more intricate synchronization logic.

When to Use Each

Start with coarse-grained locks for simplicity. If profiling reveals your lock is a performance bottleneck with threads contending heavily, consider fine-grained locking—but only if threads truly access independent data. The added complexity must justify the performance gain.

Key Takeaway:
Coarse-grained locks are simple but limit concurrency by protecting large regions; fine-grained locks boost parallelism by protecting smaller pieces but require more complex code and careful coordination.