Pavel Voronin
Pavel Voronin

Reputation: 13985

What provides spinlocks effectiveness?

Spinlocks may be effective only on systems with real parallelism i.e. multicore/processor systems. That is not surprising due to their design.

Nonetheless, threads sharing the resource must execute on different cores. Otherwise situation is similar to uniprocessor system.

Is is just the matter of probability or scheduler tries to put interlocking threads on different CPUs to provide real concurrency?

Upvotes: 3

Views: 265

Answers (2)

Kris Vandermotten
Kris Vandermotten

Reputation: 10201

When two threads are involved, spinlocks may be effective because of the probability that while one thread is waiting, the other thread releases the lock. You are thus correct that there are no guarantees, and a lot of probability is involved. As a result, you wait for locks with a spinlock only with locks that are held for a very short period of time. Because the thread that was acquiring the lock obviously was executing when the lock was acquired, there is a high probability that the thread is still executing to release the lock if that thread holds it for a very short time.

However, spinlocks can be effective also when IO is involved, i.e. when a thread is not waiting on another thread, but on a hardware event signaling that data is coming in, especially if that data is expected very soon (e.g. waiting on a hardware function being executed).

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 941317

The cost of a thread-context switch is the reason why spinlocks can be useful. The usual number that's quoted is between 2000 and 10,000 cpu cycles for a switch on Windows. Cost that's associated by having to store and reload the processor state and the stalls due to the guaranteed cache misses. This is pure overhead, nothing useful gets done.

So a program can perform better if it waits for a lock to become available, burning up several thousand cycles and periodically trying to enter the lock. Which avoids the context switch if the lock is expected to becomes available quickly.

There is no timer available to wait for such short durations, it is implemented by actually burning cycles with a small loop. Spinning. This is supported at the processor level, the dedicated PAUSE machine code instruction is available to reduce the power consumed while spinning on Intel/AMD cores. Thread.Yield() and Thread.SpinWait() in .NET take advantage of it.

Actually using a spinlock effectively in code can be tricky, it of course only works well if the odds to acquire the lock are high enough. If they are not then spinlocking is actively harmful since it delays a context switch, one that might be required to get another thread to regain the processor and release the lock. The .NET 4.0 SpinLock class is useful, it generates ETW events for failed spins. Not otherwise well documented.

Upvotes: 5

Related Questions