Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any examples in the .Net framework that use spinlock or spinwait?

I had a look at the concurrent collections but they appear to use normal locking underneath the hood. Are there any good examples in the .Net framework that use this locking construct?


I initially looked at ConcurrentDictionary. I saw it was using normal locks but the BlockingCollection class uses SpinWait in its internal methods.

like image 904
uriDium Avatar asked Jun 28 '11 11:06

uriDium


People also ask

Where is SpinLock used?

Spin locks are a low-level synchronization mechanism suitable primarily for use on shared memory multiprocessors. When the calling thread requests a spin lock that is already held by another thread, the second thread spins in a loop to test if the lock has become available.

What is SpinLock OS?

Spinlock is a locking system mechanism. It allows a thread to acquire it to simply wait in loop until the lock is available i.e. a thread waits in a loop or spin until the lock is available. Spinlock is held for a short period of time. Spinlock are useful in multiprocessor system.


3 Answers

Pretty much any of the low-lock concurrent collection class will likely use some combination of SpinWait and Yield. Though ConcurrentDictionary is one notable exception. The list of classes I found include the following.

  • ManualResetEventSlim
  • SemaphoreSlim
  • SpinLock
  • Barrier
  • ReaderWriterLockSlim
  • ConcurrentQueue
  • ConcurrentStack
  • BlockingCollection
like image 131
Brian Gideon Avatar answered Sep 22 '22 15:09

Brian Gideon


What do you mean by normal locking ? Some kind of lock(object) { ... } construct ?

If yes, you should look at ConcurrentStack for example, it uses a SpinWait for its job.

like image 39
user703016 Avatar answered Sep 24 '22 15:09

user703016


ConcurrentStack and ConcurrentQueue are lock-free collections, however ConcurrentDictionary, ConcurrentBag are using locks. BlockingCollections is just a container so it is not a collection by itself, it has to wrap other threadsafe collections, for example var bc = new BlockingCollection(new ConcurrentStack());

this is an introductory article about how to use SpinWait in lock-free code http://www.emadomara.com/2011/08/spinwait-and-lock-free-code.html

like image 34
Emad Omara Avatar answered Sep 24 '22 15:09

Emad Omara