Spinlock vs Busy wait

Please explain why Busy Waiting is usually not favored, while Spinning is often perceived as good. As far as I can tell, they both spin endlessly until some condition is met.

+7
spinlock
source share
2 answers

A spin-lock is usually used when there is a low conflict for a resource, and therefore the CPU will only do a few iterations before it can move to productive work. However, library implementations of lock functions often use spin locks, followed by regular locks. Regular locking is used if the resource cannot be obtained within a reasonable time. This is done to reduce overhead by using context switches in settings, where locks are usually executed quickly.

The term wait tends to mean that you are ready to spin and wait for a change in the hardware register or in memory. This term does not necessarily mean blocking, but it involves waiting in a closed loop, repeatedly exploring the change.

You might want to use the wait to detect some kind of change in the environment that you want to respond to immediately. Thus, the spin-lock function is implemented using busy waiting. Waiting is useful in any situation where a very low latency response is more important than wasting processor cycles (for example, in some types of embedded programming).

This includes the terms "lock-free" and "wait-free":

So-called blocking algorithms tend to use tight wait with CAS , but the assertion in normal situations is so low that the processor usually has to iterate just a few times.

So-called lifeless algorithms do not expect to wait at all.

(Note that “no lock” and “no wait” is used somewhat differently in academic contexts, see the Wikipedia article on Non-Blocking Algorithms .)

+3
source share

When you understand the exact reason for the rule and have detailed knowledge of the platform and applications, you know when to break this rule. Spinlocks are implemented by specialists who fully understand the platform on which they are developed, and the alleged spyware applications.

The problems with lively animation are numerous, but most platforms have solutions for them. The problems include:

  • For processors with a hyperthread, the expected wait thread may starve another thread in the same physical core, even what it expects.
  • When you are busy, wait, when you finally get the resource you are waiting for, you take the mother of all the incorrectly predicted branches.
  • Busy waiting interferes with CPU power management.
  • Busy waiting can saturate the internetwork buses, because conducting verification causes synchronization synchronization traffic.

But people who develop spin blocks understand all these problems and know exactly how to mitigate them on the platform. They do not write naive spinning code; they write intelligent spinning code.

So yes, they are both closed endlessly until some condition is met, but they will go differently.

-2
source share

All Articles