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

3

10

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.

Welkin answered 28/6, 2011 at 11:31 Comment(4)
Why would you do that? spin lock is a busy waiting mechanism, i.e. using resources without doing anything usefulRodman
Purely educational. I don't think I would ever need to do this. But I just want to learn more about it and have a look at a decent example. Most examples are quite contrived at best.Welkin
That you can't seem to find real life examples already says a lot in my opinion.Rodman
@Daniel: true :). But they included it for a reason. I just want to know more about it.Welkin
D
4

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.

Dekameter answered 28/6, 2011 at 12:5 Comment(0)
M
5

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
Myeshamyhre answered 28/6, 2011 at 21:16 Comment(0)
D
4

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.

Dekameter answered 28/6, 2011 at 12:5 Comment(0)
R
2

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

Rompers answered 12/8, 2011 at 2:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.