Why everyone states that SpinLock is faster? [closed] Why everyone states that SpinLock is faster? [closed] multithreading multithreading

Why everyone states that SpinLock is faster? [closed]


You are just not testing a scenario where SpinLock can improve the threading. The core idea behind a spin-lock is that a thread-context switch is very expensive operation, costing between 2000 and 10,000 cpu cycles. And that if it is likely that a thread can acquire a lock by waiting for a bit (spinning) then the extra cycles burned waiting can pay off by avoiding the thread context switch.

So basic requirements is that the lock is held for a very short time, which is true in your case. And that there are reasonable odds that the lock can be acquired. Which is not true in your case, the lock is heavily contested by no less than 24 threads. All spinning and burning core without having a chance to acquire the lock.

In this test Monitor will work best since it queues threads waiting to acquire the lock. They are suspended until one of them has a chance to acquire the lock, released from the wait queue when the lock is released. Giving them all a fair chance to take a turn, thus maximizing the odds that they'll all finish at the same time. Interlocked.Increment is not bad either but can't provide a fairness guarantee.

It can be pretty hard to judge whether Spinlock is the right approach up front, you have to measure. A concurrency analyzer is the right kind of tool.