3 ms·
A simple reasoning on why spinlock is slower than mutex in a heavily contested situation. A thread (S1) attempting to acquire a spinlock will busy looping to h
by ww520 7y ago
A simple reasoning on why spinlock is slower than mutex in a heavily contested situation.
A thread (S1) attempting to acquire a spinlock will busy looping to hog all of its time slice, preventing other threads (S2) from utilizing the CPU to free the lock.
S1: [**busy spinning**][..waiting........][**lock & run*****]
S2: [..waiting........][**run & unlock***][..waiting........]
A thread (M1) attempting to acquire a mutex will sleep to give up its time slice, letting other threads (M2) to utilize the CPU and thus have a chance to free the lock. The given up time slice can be very substantial, leading to much better performance.
M1: [sleep][..waiting........][**lock & run*****]
M2: [.....][**run & unlock***][..waiting........]
If one really really wants to use spinlock, the way to use it correctly is to boost the priority of the thread holding the lock to make sure it got priority to run over all else, so that it can finish its work quickly and release the lock.
S1: lower priority [..waiting........][**lock & run*****] higher priority
S2: higher priority [**run & unlock***] lower priority [..waiting........]
I assume the benchmark and the user-mode spinlock doesn't do that, and thus has the measured problem. OS/kernel would have a better idea to raise and lower priority with spinlock than user-mode code.
- imtringued 7y ago> If one really really wants to use spinlock You will also have to make sure that your application threads are pinned to specific cores and that the number of threads is smaller than the number of cores because you want to keep one thread free to run non critical code. Spinlocks are like full plate armor. Very effective but incredibly cumbersome to use.