{"id":3516,"date":"2012-03-26T16:30:00","date_gmt":"2012-03-26T16:30:00","guid":{"rendered":"https:\/\/test.simple-talk.com\/uncategorized\/inside-the-concurrent-collections-concurrentbag\/"},"modified":"2017-10-26T15:16:19","modified_gmt":"2017-10-26T15:16:19","slug":"inside-the-concurrent-collections-concurrentbag","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/blogs\/inside-the-concurrent-collections-concurrentbag\/","title":{"rendered":"Inside the Concurrent Collections: ConcurrentBag"},"content":{"rendered":"<p>Unlike the other concurrent collections, <code>ConcurrentBag<\/code> does not really have a non-concurrent analogy. As stated in the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/dd381779.aspx\">MSDN documentation<\/a>, ConcurrentBag is optimised for the situation where the same thread is both producing and consuming items from the collection. We&#8217;ll see how this is the case as we take a closer look. Again, I recommend you have <code>ConcurrentBag<\/code> open in a decompiler for reference.<\/p>\n<h4>Thread Statics<\/h4>\n<p>ConcurrentBag makes heavy use of thread statics &#8211; static variables marked with <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/System.ThreadStaticAttribute.aspx\"><code>ThreadStaticAttribute<\/code><\/a>. This is a special attribute that instructs the CLR to scope any values assigned to or read from the variable to the executing thread, not globally within the AppDomain.<\/p>\n<p>This means that if two different threads assign two different values to the same thread static variable, one value will not overwrite the other, and each thread will see the value they assigned to the variable, separately to any other thread. This is a very useful function that allows for ConcurrentBag&#8217;s concurrency properties.<\/p>\n<p>You can think of a thread static variable:<\/p>\n<pre>[ThreadStatic]\r\nprivate static int m_Value;<\/pre>\n<p>as doing the same as:<\/p>\n<pre>private static Dictionary&lt;Thread, int&gt; m_Values;<\/pre>\n<p>where the executing thread&#8217;s identity is used to automatically set and retrieve the corresponding value in the dictionary.<\/p>\n<p>&nbsp;<\/p>\n<p>In .NET 4, this usage of <code>ThreadStaticAttribute<\/code> is encapsulated in the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/dd642243.aspx\"><code>ThreadLocal<\/code><\/a> class.<\/p>\n<h4>Lists of lists<\/h4>\n<p>ConcurrentBag, at its core, operates as a linked list of linked lists:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/blogbits\/simon.cooper\/ConcurrentBag.png\" alt=\"ConcurrentBag.png\" \/><\/p>\n<p>Each outer list node is an instance of <code>ThreadLocalList<\/code>, and each inner list node is an instance of <code>Node<\/code>. Each outer <code>ThreadLocalList<\/code> is owned by a particular thread, accessible through the thread local <code>m_locals<\/code> variable:<\/p>\n<pre>private ThreadLocal&lt;ThreadLocalList&lt;T&gt;&gt; m_locals<\/pre>\n<p>It is important to note that, although the <code>m_locals<\/code> variable is thread-local, that only applies to accesses through that variable. The objects referenced by the thread (each instance of the <code>ThreadLocalList<\/code> object) are normal heap objects that are not specific to any thread. Thinking back to the Dictionary analogy above, if each value stored in the dictionary could be accessed by other means, then any thread could access the value belonging to other threads using that mechanism. Only reads and writes to the variable defined as thread-local are re-routed by the CLR according to the executing thread&#8217;s identity.<\/p>\n<p>&nbsp;<\/p>\n<p>So, although <code>m_locals<\/code> is defined as thread-local, the <code>m_headList<\/code>, <code>m_nextList<\/code> and <code>m_tailList<\/code> variables aren&#8217;t. This means that any thread can access all the thread local lists in the collection by doing a linear search through the outer linked list defined by these variables.<\/p>\n<h4>Adding items<\/h4>\n<p>So, onto the collection operations. First, adding items. This one&#8217;s pretty simple. If the current thread doesn&#8217;t already own an instance of <code>ThreadLocalList<\/code>, then one is created (or, if there are lists owned by threads that have stopped, it takes control of one of those). Then the item is added to the head of that thread&#8217;s list.<\/p>\n<p>That&#8217;s it. Don&#8217;t worry, it&#8217;ll get more complicated when we account for the other operations on the list!<\/p>\n<h4>Taking &amp; Peeking items<\/h4>\n<p>This is where it gets tricky. If the current thread&#8217;s list has items in it, then it peeks or removes the head item (<em>not<\/em> the tail item) from the local list and returns that. However, if the local list is empty, it has to go and steal another item from another list, belonging to a different thread. It iterates through all the thread local lists in the collection using the <code>m_headList<\/code> and <code>m_nextList<\/code> variables until it finds one that has items in it, and it steals one item from that list. Up to this point, the two threads had been operating completely independently. To steal an item from another thread&#8217;s list, the stealing thread has to do it in such a way as to not step on the owning thread&#8217;s toes.<\/p>\n<p>Recall how adding and removing items both operate on the head of the thread&#8217;s linked list? That gives us an easy way out &#8211; a thread trying to steal items from another thread can pop in round the back of another thread&#8217;s list using the <code>m_tail<\/code> variable, and steal an item from the back without the owning thread knowing anything about it. The owning thread can carry on completely independently, unaware that one of its items has been nicked.<\/p>\n<p>However, this only works when there are at least 3 items in the list, as that guarantees there will be at least one node between the owning thread performing operations on the list head and the thread stealing items from the tail &#8211; there&#8217;s no chance of the two threads operating on the same node at the same time and causing a race condition.<\/p>\n<p>If there&#8217;s less than three items in the list, then there does need to be some synchronization between the two threads. In this case, the lock on the <code>ThreadLocalList<\/code> object is used to mediate access to a thread&#8217;s list when there&#8217;s the possibility of contention.<\/p>\n<h4>Thread synchronization<\/h4>\n<p>In <code>ConcurrentBag<\/code>, this is done using several mechanisms:<\/p>\n<ol>\n<li>Operations performed by the owner thread only take out the lock when there are less than three items in the collection. With three or greater items, there won&#8217;t be any conflict with a stealing thread operating on the tail of the list.<\/li>\n<li>If a lock isn&#8217;t taken out, the owning thread sets the list&#8217;s <code>m_currentOp<\/code> variable to a non-zero value for the duration of the operation. This indicates to all other threads that there is a non-locked operation currently occuring on that list.<\/li>\n<li>The stealing thread always takes out the lock, to prevent two threads trying to steal from the same list at the same time.<\/li>\n<li>After taking out the lock, the stealing thread spinwaits until <code>m_currentOp<\/code> has been set to zero before actually performing the steal. This ensures there won&#8217;t be a conflict with the owning thread when the number of items in the list is on the 2-3 item borderline. If any add or remove operations are started in the meantime, and the list is below 3 items, those operations try to take out the list&#8217;s lock and are blocked until the stealing thread has finished.<\/li>\n<\/ol>\n<p>&nbsp;<\/p>\n<p>This allows a thread to steal an item from another thread&#8217;s list without corrupting it. What about synchronization in the collection as a whole?<\/p>\n<h4>Collection synchronization<\/h4>\n<p>Any thread that operates on the collection&#8217;s global structure (accessing anything outside the thread local lists) has to take out the collection&#8217;s global lock &#8211; <code>m_globalListsLock<\/code>. This single lock is sufficient when adding a new thread local list, as the items inside each thread&#8217;s list are unaffected. However, what about operations (such as <code>Count<\/code> or <code>ToArray<\/code>) that need to access every item in the collection?<\/p>\n<p>In order to ensure a consistent view, all operations on the collection are stopped while the count or <code>ToArray<\/code> is performed. This is done by freezing the bag at the start, performing the global operation, and unfreezing at the end:<\/p>\n<ol>\n<li>The global lock is taken out, to prevent structural alterations to the collection.<\/li>\n<li><code>m_needSync<\/code> is set to true. This notifies all the threads that they need to take out their list&#8217;s lock irregardless of what operation they&#8217;re doing.<\/li>\n<li>All the list locks are taken out in order. This blocks all locking operations on the lists.<\/li>\n<li>The freezing thread waits for all current lockless operations to finish by spinwaiting on each <code>m_currentOp<\/code> field.<\/li>\n<\/ol>\n<p>The global operation can then be performed while the bag is frozen, but no other operations can take place at the same time, as all other threads are blocked on a list&#8217;s lock. Then, once the global operation has finished, the locks are released, <code>m_needSync<\/code> is unset, and normal concurrent operation resumes.<\/p>\n<h4>Concurrent principles<\/h4>\n<p>That&#8217;s the essence of how <code>ConcurrentBag<\/code> operates. Each thread operates independently on its own local list, except when they have to steal items from another list. When stealing, only the stealing thread is forced to take out the lock; the owning thread only has to when there is the possibility of contention. And a global lock controls accesses to the structure of the collection outside the thread lists. Operations affecting the entire collection take out all locks in the collection to freeze the contents at a single point in time.<\/p>\n<p>So, what principles can we extract here?<\/p>\n<ol>\n<li><strong>Threads operate independently<\/strong>\n<p>Thread-static variables and <code>ThreadLocal<\/code> makes this easy. Threads operate entirely concurrently on their own structures; only when they need to grab data from another thread is there any thread contention.<\/p>\n<\/li>\n<li><strong>Minimised lock-taking<\/strong>\n<p>Even when two threads need to operate on the same data structures (one thread stealing from another), they do so in such a way such that the probability of actually blocking on a lock is minimised; the owning thread always operates on the head of the list, and the stealing thread always operates on the tail.<\/p>\n<\/li>\n<li><strong>Management of lockless operations<\/strong>\n<p>Any operations that don&#8217;t take out a lock still have a &#8216;hook&#8217; to force them to lock when necessary. This allows all operations on the collection to be stopped temporarily while a global snapshot is taken. Hopefully, such operations will be short-lived and infrequent.<\/p>\n<\/li>\n<\/ol>\n<p>That&#8217;s all the concurrent collections covered. I hope you&#8217;ve found it as informative and interesting as I have. Next, I&#8217;ll be taking a closer look at <code>ThreadLocal<\/code>, which I came across while analyzing <code>ConcurrentBag<\/code>. As you&#8217;ll see, the operation of this class deserves a much closer look.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Unlike the other concurrent collections, ConcurrentBag does not really have a non-concurrent analogy. As stated in the MSDN documentation, ConcurrentBag is optimised for the situation where the same thread is both producing and consuming items from the collection. We&#8217;ll see how this is the case as we take a closer look. Again, I recommend you&#8230;&hellip;<\/p>\n","protected":false},"author":186659,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[2],"tags":[],"coauthors":[35902],"class_list":["post-3516","post","type-post","status-publish","format-standard","hentry","category-blogs"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/3516","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/186659"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=3516"}],"version-history":[{"count":2,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/3516\/revisions"}],"predecessor-version":[{"id":75083,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/3516\/revisions\/75083"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=3516"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=3516"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=3516"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=3516"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}