How much does one lock guard
Granularity is how much shared state a single lock protects. A coarse lock guards a large structure with one mutex; a fine lock splits the structure so different parts have their own mutexes.
Coarse grained locking
One big lock is simple and easy to reason about. There is little chance of deadlock because there is essentially one lock to take. The cost is parallelism: every operation, even on unrelated data, serializes behind the same lock, so contention rises fast.
Fine grained locking
Many small locks let independent operations proceed in parallel, raising throughput under load. The price is complexity:
- More locks mean more chances for deadlock, requiring a consistent lock ordering
- Acquiring several small locks adds overhead per operation
- The code is harder to read and to prove correct
Finding the balance
The right granularity depends on the access pattern. If operations rarely overlap on the same data, fine grained pays off. If they almost always touch the whole structure anyway, a coarse lock is simpler and just as fast. Profile first, then split only the locks that are actually hot.
Key idea
Coarse locks trade parallelism for simplicity, fine locks trade simplicity and deadlock risk for parallelism, so split only the hot locks.