What is Spinlock: Simple Explanation and Usage in OS
spinlock is a simple locking mechanism used in operating systems to protect shared resources by making a thread repeatedly check (or "spin") until the lock becomes available. It avoids putting the thread to sleep, making it efficient for short waits but costly if held for long.How It Works
A spinlock works like a busy-wait loop where a thread keeps checking if a lock is free. Imagine a single bathroom in an office where employees keep knocking on the door until it is free instead of waiting outside quietly. This constant checking is called "spinning."
When a thread wants to enter a critical section (a part of code that accesses shared data), it tries to acquire the spinlock. If the lock is already taken, the thread keeps looping, checking repeatedly until the lock is released. Once free, the thread grabs the lock and proceeds.
This method avoids the overhead of putting the thread to sleep and waking it up, which can be slow. However, it wastes CPU cycles while spinning, so it is best used when the lock is expected to be held for a very short time.
Example
This example shows a simple spinlock implementation in C using atomic operations to safely acquire and release the lock.
#include <stdatomic.h> #include <stdio.h> #include <threads.h> atomic_flag lock = ATOMIC_FLAG_INIT; void spinlock_acquire() { while (atomic_flag_test_and_set_explicit(&lock, memory_order_acquire)) { // Busy wait (spin) until the lock is free } } void spinlock_release() { atomic_flag_clear_explicit(&lock, memory_order_release); } int shared_counter = 0; int worker(void *arg) { for (int i = 0; i < 100000; i++) { spinlock_acquire(); shared_counter++; spinlock_release(); } return 0; } int main() { thrd_t t1, t2; thrd_create(&t1, worker, NULL); thrd_create(&t2, worker, NULL); thrd_join(t1, NULL); thrd_join(t2, NULL); printf("Final counter value: %d\n", shared_counter); return 0; }
When to Use
Use a spinlock when you expect the lock to be held for a very short time and the overhead of putting a thread to sleep and waking it up is higher than just waiting actively. This is common in low-level operating system code or real-time systems where quick locking is critical.
For example, spinlocks are useful in multiprocessor systems where threads run on different CPUs and the wait time is minimal. They are not suitable for long waits or single-processor systems because spinning wastes CPU resources.
Key Points
- Spinlocks use busy waiting instead of sleeping.
- They are efficient for very short lock durations.
- Spinning wastes CPU if the lock is held long.
- Commonly used in multiprocessor and real-time systems.
- Not suitable for long waits or single-core CPUs.