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.

Dariusz Woźniak
  • 9,640
  • 6
  • 60
  • 73
uriDium
  • 13,110
  • 20
  • 78
  • 138
  • Why would you do that? spin lock is a busy waiting mechanism, i.e. using resources without doing anything useful – Daniel Hilgarth Jun 28 '11 at 11:35
  • 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. – uriDium Jun 28 '11 at 11:44
  • That you can't seem to find real life examples already says a lot in my opinion. – Daniel Hilgarth Jun 28 '11 at 11:45
  • @Daniel: true :). But they included it for a reason. I just want to know more about it. – uriDium Jun 28 '11 at 11:51

3 Answers3

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
Brian Gideon
  • 47,849
  • 13
  • 107
  • 150
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.

user703016
  • 37,307
  • 8
  • 87
  • 112
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

Emad Omara
  • 512
  • 4
  • 3