About Concurrent Collections

One of the most useful additions to the .Net 4.0 base class library is the System.Collections.Concurrent namespace, which contains an all-new set of lock-free thread.

However, these collections are noticeably different from their classical counterparts.  There is no simple ConcurrentList<T> that you can drop into your code so that it will become thread-safe.  Instead, the new namespace has a queue, a stack, and some new thing called a bag, as well as ConcurrentDictionary<TKey, TValue> that largely resembles classical dictionaries.  It also has a BlockingCollection<T> class that wraps a concurrent collection and blocks until operations can succeed.

Many people have complained that Microsoft chose to provide an entirely new set of classes, rather than adding synchronized versions of the existing collections. 

In truth, however, creating this new set of classes is the correct – and, in fact, only – choice.  Ordinary synchronized are rarely useful and will not make a program thread-safe.  In general, slapping locks everywhere does not make a program thread-safe!  Rather, that will either not help (if there aren’t enough locks) or, if there are enough locks, result in deadlocks or a program that never runs more than one thread at a time.  (depending on how many different objects get locked)

Collections in particular have two fundamental issues when used on multiple threads.

The first, and simpler, issue is that the collection classes themselves are not thread-safe.  If two threads add to a List<T> at the same exact time, one thread is likely to overwrite the other thread’s value.  A synchronized version of List<T> with a lock around every method would solve this problem.

The bigger issue is that any code that uses a List<T> is unlikely to be thread-safe, even if the list itself is thread-safe.  For example. you can never enumerate over a multi-threaded list, because another thread may change the list at any time, invalidating the enumerator.  This issue could be solved by taking a read lock for the lifetime of the enumerator.  However, that is also a bad idea, since if any client code forgets to dispose the enumerator, the collection will deadlock when written to.

You also cannot use indices.  It is never safe to get, set, or remove an item at an index, because another thread might remove that item or clear the entire collection between your index check and the operation.

To solve all of these problems, you need thread-safe collections that provide atomic operations.  This is why all of the concurrent collections have such strange methods, including TryPop, AddOrUpdate, and TryTake.  These methods perform their operations atomically, and return false if the collection was empty (as appropriate; consult the documentation for actual detail).  Thus, the new concurrent collections can be used reliably in actual multi-threaded code without a separate layer of locks.

13 comments:

You say "These methods perform their operations atomically, and return false if the collection was empty (as appropriate; consult the documentation for actual detail)."

Reading the documentation for ConcurrentQueue.TryDequeue, I only see it say that it returns false if the Dequeue FAILS. It doesn't say why it might fail. Are you saying that it only fails if the Queue is empty? That there is no synchronization failure I need to worry about, or retry for?

Reading the source, ConcurrentQueue.TryDequeue will only return false if the queue is empty.

"If two threads add to a List at the same exact time, one thread is likely to overwrite the other thread’s value" does mean "thread-unsafe" only incoherent or undesired state of thread

Greetings! I know this is somewhat off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form? I'm using the same blog platform as yours and I'm having problems finding one? Thanks a lot!
geometry dash pc| happy wheels game |happy wheels |five nights at freddy's |agario slitherio

Him with you watching TV, cycling, eating, going out, going to sleep ... You memorized the jokes, the jokes of him, so they still make you be laughing. Who listens to the story you tell
baixar snapchat l play run 2 l geometry dash l retrica photo l baixar musicas gratis l b612 app

You have posted a detailed document having full of latest information. I read this whole content and really liked it. Thanks for sharing.
* hotmail sign up

Thank you both for sharing Holy Mass with us each day FNAF Sister Location Juegos Friv Friv 2018 to make yourselves available Friv Twizl Jeux De Twizl Juegos De FNAF Sister Location when we were called out late at night and any other time and for your support and encouragement in every respect. Juegos Friv 2021 Juegos Twizl Juegos Yepi 2017 Juegos De Twizl

nice blog, thank you
Danke, dafur dass Ihr jeden Tag mit uns die Hl. Messe gefeiert habt, fur all die Reparaturen im ganzen Haus Friv 10 Friv 2018 Friv 2019 fur Euere Bereitschaft Friv 10 Friv 20 Friv 2 immer zur Verfugung zu stehen Geometry Dash Twizl Twizy Twizl Danke, dass Sie Ihr Muhen um den Aufbau des Leibes Christi mit uns teilten.

Senhor Deputado Cashman, agradeço-lhe a informação. Juegos Friv Jogos Friv Friv4school A todos que partilham e trabalham sob estas mesmas convicções e princípios Jeux De Friv Juegos De Roblox Zoxy Mais uma vez, obrigada ao Parlamento por comungar da visão que informa a nova política dos consumidores Juegos Kizi Juegos Yepi Twizl Zoxy assente no mercado - a visão de um mercado de consumidores informados e capacitados que procuram e usufruem, com confiança,

The article you have shared here very good. This is really interesting information for me. Thanks for sharing!
hotmail login |hotmail sign in |free hotmail login


Wir danken Ihnen
Friv4school Gry Friv Juegos Friv dass Sie diese Hoffnung mit uns teilen und diesen Schritt auf dem Pilgerweg des Vertrauens Friv Juegos Friv Gry Friv mit uns gegangen sind. Juegos Friv Juegos De Friv Ihnen hiermit die gewünschten Informationen vermitteln zu können. Yepi Juegos Friv wir danken Ihnen für das Interesse an unseren Produkten und hoffe

Gracias por compartir sus ideas con nosotros. Friv Games Gry Friv gracias por la detallada información. Juegos Friv Gry Friv Friv Gracias por vuestras reacciones a las transmisiones que os han hecho. Friv Games Juegos Friv Acogemos con agrado los comentarios de los lectores.

Very nice. Posts shared useful information and meaningful life, I'm glad to be reading this article and hope to soon learn the next article. thank you
minecraft
a10 games
g9g games
4223 games
yoob games
hopy games
huz 10 games
kizi hot
kizi new games
yepi games

Post a Comment