Search topics...
Operating Systems & RTOSSpinlocks and Atomic Operationsintermediate

What is a spinlock and when is it appropriate to use one?

0 upvotes
Practice with AISoon
Study the fundamentals first — Operating Systems & RTOS topic page

A spinlock is a synchronization primitive where a task repeatedly checks ("spins") in a tight loop until a lock becomes available. Unlike a mutex, which causes a blocked task to be descheduled (sleeping), a spinlock keeps the task actively running on the CPU, burning cycles while waiting.

On a single-core system, spinlocks are almost always a bad idea. If Task A holds the spinlock and Task B spins waiting for it, Task B wastes its entire time slice spinning and prevents Task A from running (if they are the same priority) or prevents lower-priority tasks from making progress. A mutex is far better because the blocked task yields the CPU, allowing other tasks (including the lock holder) to run.

Spinlocks are appropriate on multi-core systems for very short critical sections. On a dual-core MCU (e.g., ESP32, RP2040), if Core 0 holds a spinlock for just a few instructions, it is cheaper for Core 1 to spin than to perform a full context switch. The key requirement is that the lock is held for an extremely short time (microseconds). Spinlocks also require hardware atomic instructions (test-and-set, compare-and-swap) to implement correctly. On Cortex-M, LDREX/STREX (exclusive load/store) instructions provide this capability. In an embedded interview, the safe answer is: "Avoid spinlocks in user code on single-core RTOS systems; use mutexes instead. Spinlocks are suitable for multi-core systems or within the kernel itself for very brief critical sections."

Source: Operating Systems & RTOS Q&A