Should interlocked implementations based on CompareExchange use SpinWait?

My non-expert opinion is that in this particular case, where two threads occasionally call AddIfLessThan, a SpinWait is unneeded. It could be beneficial in case the two threads were both calling AddIfLessThan in a tight loop, so that each thread could make progress uninterrupted for some μsec.

Actually I made an experiment and measured the performance of one thread calling AddIfLessThan in a tight loop versus two threads. The two threads need almost four times more to make the same number of loops (cumulatively). Adding a SpinWait to the mix makes the two threads only slightly slower than the single thread.


Two threads is just not a subject for SpinWait discussion. But this code doesn't tell us how many threads can actually compete for the resource and with relatively high number of threads using of the SpinWait can become beneficial. In particular with higher number of threads the virtual queue of threads, which are trying to successfully acquire the resource, gets longer and those threads which happen to be served in the end have good chances to exceed their time slice allocated by scheduler which in turn can lead to higher CPU consumption and may affect execution of other scheduled threads even with higher priority. The SpinWait has good answer to this situation by setting some upper limit of allowed spins after which the context switching is going to be executed. So it's a reasonable trade-off between necessity to make an expensive system call in order to trigger a context switching and uncontrolled user mode CPU consumption which is under the risk to impact the other threads execution in certain situations.