3 ms·
> Why would it make more sense to "spin a limited number of times before going through the slow path to acquire a mutex"? Have you ever waited at a door for so
by scott_s 7y ago
> Why would it make more sense to "spin a limited number of times before going through the slow path to acquire a mutex"?
Have you ever waited at a door for someone, and after a long enough time, sat down on the floor? It's basically the same logic.
First, the "slow path" for acquiring a true mutex involves calling into the kernel. This is relatively expensive. At first, you hope that your waiting time will be very small. So you optimistically just spin in user-space waiting for the lock to be released. But this spinning is expensive: you're consuming the CPU doing nothing productive. Eventually, there's a basic principle to consider: the longer you wait, the more likely you are to wait longer. After along enough wait, you assume you're going to wait even longer, so it's worth it to pay the cost of calling into the kernel so that someone else who has productive work to do can do that while you're waiting.
Kernels will use spinlocks in various places because the kernel implementors know that the critical sections will be short, or they know that scheduling another task over the current one would be problematic.