How do hardware instructions like Test-and-Set and Compare-and-Swap help implement synchronization primitives?

Last updated 5 July 2026

  • These instructions do an uninterruptible read-modify-write on a memory word. Test-and-Set sets a word to 1 and returns the old value (a spinlock loops until it gets 0).

  • Compare-and-Swap writes a new value only if the current value matches an expected one, enabling lock-free algorithms. They work across cores, unlike disabling interrupts, and underpin mutexes and semaphores.

  • Caveats: spinlocks waste CPU and can be unfair. CAS suffers the ABA problem (A to B to A looks unchanged), fixed with version tags.

  • https://www.geeksforgeeks.org/operating-systems/solutions-to-critical-section-problem/
  • https://en.wikipedia.org/wiki/Test-and-set
  • https://www.youtube.com/watch?v=cd8pNNmN9fg
  • https://www.geeksforgeeks.org/operating-systems/special-machine-instructions-in-operating-system/
  • https://www.geeksforgeeks.org/operating-systems/hardware-based-solutions/
  • https://en.wikipedia.org/wiki/Compare-and-swap
  • https://medium.com/@humbertofilho_30158/operating-systems-locking-mechanisms-fa99e8b282c5
  • https://medium.com/@priyanshuanandd/synchronization-problem-and-operating-system-8422ef2f1a34
All Operating Systems interview questions