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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With