Mutexes and Invariants Across Critical Sections

Choose one protected invariant and make every update preserve it when the lock passes between threads.

Source
Anbloq
Language
English
Created
Updated
Chapters
2
Reading time
1 min
In this article2 chapters
  1. Protect the relationship rather than one assignment
  2. Keep lock scope aligned with the operations that need it

Protect the relationship rather than one assignment

A bounded queue can require a length field to equal its number of linked entries. Enqueuing changes both. If another thread can inspect the structure between those writes, separately protecting each field may still expose an inconsistent snapshot. Protect the sequence restoring the combined invariant with the same lock. An operation starting after it acquires the lock can rely on the invariant established before the previous unlock.

Keep lock scope aligned with the operations that need it

Holding a lock during unrelated slow I/O can delay everyone else without protecting more shared state. Moving I/O outside the section may need copying or version checks so its result still applies. A wait for changing shared state usually uses a condition variable. When several locks are needed, lock ordering can prevent cycles of waiting.[1][2]

References

  1. Remzi H. Arpaci-Dusseau and Andrea C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces ↩
  2. Maurice Herlihy and Nir Shavit, The Art of Multiprocessor Programming ↩