What are the basic differences between spin locks and semaphores in action?
|
|
Both manage a limited resource. I'll first describe difference between binary semaphore (mutex) and spin lock. Spin locks perform a busy wait - i.e. it keeps running loop:
It performs very lightweight locking/unlocking but if the locking thread will be preempted by other which will try to access the same resouce the second one will simply try to acquitre resource untill it run out of it CPU quanta. On the other hand mutex behave more like:
Hence if the thread will try to acquire blocked resource it will be suspended till it will be avaible for it. Locking/unlocking is much more heavy but the waiting is 'free' and 'fair'. Semaphore is a lock that is allowed to be used multiple (known from initialization) number of times - for example 3 threads are allowed to simultainusly hold the resource but no more. It is used for example in producer/consumer problem or in general in queues:
|
|||||||
|
|
Spinlocks are used in an interrupt context, where sleeping is not allowed. They poll in a tight loop, doing nothing else until the resource is acquired. Mostly used in ISRs, and more secure and efficient. Semaphores can be used in a process context, where sleeping is ok. |
||||
|
|
|
Here's my quick shot at an answer: a spin lock and a binary semaphore (which manages a resource that can only be used by one thing) are almost identical. Their distinction is that spin locks manage code to be run while binary semaphores manage some kind of singular resource (e.g. cpu time, display output) A regular semaphore, however is able to manage several threads accessing a resource that can be split among several, but is limited (e.g. memory, network bandwidth) In short, a spin-lock is likely to keep asking a semaphore if it can use a resource. (Imagine a child having to use the bathroom and waiting for someone else to finish.) Sources: Introduction to Systems Programming, Operating Systems, and wikipedia |
|||
|
|