3 ms·
You're getting some incomplete answers to your question. Both a mutex and a spinlock is used to guarantee that a set of instructions are only invoked by a singl
by banachtarski 7y ago
You're getting some incomplete answers to your question. Both a mutex and a spinlock is used to guarantee that a set of instructions are only invoked by a single thread of computation at once (with some variation; some mutex types permit multiple readers for example).
The difference is actually in the implementation of the mutual exclusion. A mutex is generally a system call which often starts as a spin lock before the system call is invoked (which is an assembly routine that changes the process privilege level and cedes control to the host operating system). A spinlock literally "spins" in a loop until an atomic flag or semaphore indicates that it can enter the protected region. When it does, it atomically sets the flag so that it has exclusive access. Because a spinlock does not interact directly with the OS scheduler, it needs a pause instruction or yield syscall at some point in its loop (or every few interations). Failure to do so introduces pathological scheduling problems as outlined in the article.
Spinlocks are sometimes used because it is believed that the odds of a collision are very low, and the cost of a syscall is perceived as being high to the developer. However, it's something that should only be used if you know what you're doing, and its behavior is subject to not only the OS, but also the hardware you run on.