A spinlock is a lock that operates by disabling scheduler and possibly interrupts (irqsave variant) on that particular core that the lock is acquired on.
The term busy-waiting tends to mean that you are willing to spin and wait for a change in a hardware register or a memory location. The term does not necessarily mean locking, but it does imply waiting in a tight loop, repeatedly probing for a change.
You may want to use busy-waiting in order to detect some kind of change in the environment that you want to respond to immediately. So a spin-lock is implemented using busy-waiting. Busy-waiting is useful in any situation where a very low latency response is more important than wasting CPU cycles (like in some types of embedded programming).
Spinlock vs Mutex
Advantages of Spinlock
Disable Scheduler
It is different from a mutex in that it disables scheduling so only your thread can run while spinlock is held. A mutex allows other higher priority threads to be scheduled in while it is held but does not allow them to simultaneously execute the protected section. Because spinlocks disable multitasking you can not take a spinlock and then call some other code that will try to acquire a mutex. Your code inside the spinlock section must never sleep (code typically sleeps when it encounters a locked mutex or empty semaphore).
No queue
Another difference with a mutex is that threads typically queue for a mutex so a mutex underneath has a queue. Whereas spinlock just ensures that no other thread will run even if it has to. Therefore, you must never hold a spinlock when calling functions outside your file that you are not sure will not sleep.
Disable Interrupts
When you want to share your spinlock with an interrupt you must use irqsave variant. This will not just disable scheduler but will also disable interrupts. It makes sense right? Spinlock works by making sure nothing else will run. If you don't want an interrupt to run you disable it and proceed safely into the critical section.
Disadvantage of Spinlock
On multicore machine a spinlock will actually spin waiting for another core that holds the lock to release it. This spinning only happens on multicore machines because on single core ones it can not happen (you either hold spinlock and proceed or you never run until the lock is released).
How can we avoid Spinlock spinning continously?
- Switch to a different thread while waiting. This typically involves attaching the current thread to a queue of threads waiting for the lock, followed by switching to another thread that is ready to do some useful work. This scheme also has the advantage that it guarantees that resource starvation does not occur as long as all threads eventually relinquish locks they acquire and scheduling decisions can be made about which thread should progress first. Spinlocks that never entail switching, usable by real-time operating systems, are sometimes called raw spinlocks.
Comments
Post a Comment