2

While looking into synchronization primitives offered by .net, I came across SpinLock and SpinWait. From the looks of it, it appears to me that SpinWait would always be the way to go..why would one continue busy waiting without relinquishing CPU when the thread has to actually be waiting for a signal from outside the thread? The cycles spent in these idle waits could have potentially been used by the thread that would that would be singalling and unblocking the thread thats busy-waiting.

Why does SpinLock exist? What makes it different than a simple busy-wait using a while loop? Under what circumstance would one want to use SpinLock over SpinWait?

Aadith Ramia
  • 10,005
  • 19
  • 67
  • 86
  • This is been discussed in the below stack over flow link http://stackoverflow.com/questions/1091135/whats-the-purpose-of-thread-spinwait-method. – shri Jan 07 '16 at 04:23
  • 1
    SpinWait just does the spinning, not the locking. You'd consider it for example when using the *lock* keyword or Monitor, they don't spin. Monitor only spins when you specify a timeout. Never micro-optimize threaded code, only do this when you have evidence from a concurrency analyzer that context switch cost is dominant. – Hans Passant Jan 07 '16 at 08:16

1 Answers1

3

Typically, the implementation of a spin lock will already understand how to avoid depriving other cores (or other threads sharing this core) of execution resources. So you shouldn't have to worry about fighting the thread that's going to unblock you. And, of course, a sub-optimal implementation of a spin lock wouldn't be a very useful thing. (Though that doesn't stop people from writing them!)

If you know the wait will be for a very short period of time because the lock is only held while trivial operations are accomplished, then the spin lock has a bit less overhead than an adaptive spin lock that switches to waiting. A good example would be a lock that protects a heavily-contended, fast collection (such as a hash) and is only held while an object is inserted in, removed from, or found in the collection in an application where nearly all threads access the collection.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278