How might a class like .NET's ConcurrentBag be implemented?

后端 未结 5 802
夕颜
夕颜 2021-02-07 21:49

I find myself very intrigued by the existence of a ConcurrentBag class in the upcoming .NET 4.0 framework:

Bags are useful for storing objects wh

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-07 22:49

    There's some good info on ConcurrentBag here: http://geekswithblogs.net/BlackRabbitCoder/archive/2011/03/03/c.net-little-wonders-concurrentbag-and-blockingcollection.aspx

    The way that the ConcurrentBag works is to take advantage of the new ThreadLocal type (new in System.Threading for .NET 4.0) so that each thread using the bag has a list local to just that thread.

    This means that adding or removing to a thread-local list requires very low synchronization. The problem comes in where a thread goes to consume an item but it’s local list is empty. In this case the bag performs “work-stealing” where it will rob an item from another thread that has items in its list. This requires a higher level of synchronization which adds a bit of overhead to the take operation.

提交回复
热议问题