Spinlocks - aryanjoshi0823/5143-Operating-System GitHub Wiki
What is a Spinlock?
A spinlock is a synchronization primitive used to protect shared resources by allowing only one thread or process to access them at a time. It employs a busy-waiting mechanism, where a thread continuously checks the lock until it becomes available, instead of sleeping or pausing.
Analogy:
Imagine a locked door allowing one person in a room at a time. Instead of waiting patiently, people keep knocking repeatedly to check if the door is unlocked. This constant checking is the essence of busy-waiting in spinlocks.
Characteristics of Spinlocks:
- Efficient for Short Waits: Works well when the critical section is brief.
- Lightweight: Avoids complex thread-blocking mechanisms.
- CPU Intensive: Consumes CPU cycles while waiting, making it less suitable for long waits or high contention scenarios.
Drawbacks of Spinlocks
- Inefficient for Long Waits: Busy-waiting wastes CPU cycles if the critical section is held for an extended period.
- High Contention: Multiple threads spinning can lead to performance degradation.
- Context Switching Overhead: Frequent preemption interrupts spinning threads, further reducing efficiency.
When to Use Spinlocks?
Spinlocks are ideal when:
- The critical section is small and quick to execute.
- Thread contention for the resource is low.