5 // Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
7 // Copyright (c) 2009 Jérémie "Garuma" Laval
9 // Permission is hereby granted, free of charge, to any person obtaining a copy
10 // of this software and associated documentation files (the "Software"), to deal
11 // in the Software without restriction, including without limitation the rights
12 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 // copies of the Software, and to permit persons to whom the Software is
14 // furnished to do so, subject to the following conditions:
16 // The above copyright notice and this permission notice shall be included in
17 // all copies or substantial portions of the Software.
19 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
29 using System.Collections;
30 using System.Collections.Generic;
31 using System.Diagnostics;
32 using System.Runtime.InteropServices;
34 using System.Threading;
35 using System.Threading.Tasks;
37 namespace System.Collections.Concurrent
40 [DebuggerDisplay ("Count={Count}")]
41 [DebuggerTypeProxy (typeof (CollectionDebuggerView<>))]
42 public class ConcurrentBag<T> : IProducerConsumerCollection<T>, IEnumerable<T>, IEnumerable
44 // We store hints in an int
48 // The container area is where bag are added foreach thread
49 ConcurrentDictionary<int, CyclicDeque<T>> container = new ConcurrentDictionary<int, CyclicDeque<T>> ();
50 // The staging area is where non-empty bag are located for fast iteration
51 ConcurrentDictionary<int, CyclicDeque<T>> staging = new ConcurrentDictionary<int, CyclicDeque<T>> ();
53 public ConcurrentBag ()
57 public ConcurrentBag (IEnumerable<T> collection) : this ()
59 foreach (T item in collection)
63 public void Add (T item)
66 CyclicDeque<T> bag = GetBag (out index);
67 bag.PushBottom (item);
68 staging.TryAdd (index, bag);
70 Interlocked.Increment (ref count);
73 bool IProducerConsumerCollection<T>.TryAdd (T element)
79 public bool TryTake (out T result)
87 CyclicDeque<T> bag = GetBag (out hintIndex, false);
90 if (bag == null || bag.PopBottom (out result) != PopResult.Succeed) {
93 foreach (var other in staging) {
94 // Try to retrieve something based on a hint
95 ret = TryGetHint (out hintIndex) && (bag = container[hintIndex]).PopTop (out result) == PopResult.Succeed;
97 // We fall back to testing our slot
98 if (!ret && other.Value != self) {
99 var status = other.Value.PopTop (out result);
100 while (status == PopResult.Abort)
101 status = other.Value.PopTop (out result);
102 ret = status == PopResult.Succeed;
103 hintIndex = other.Key;
107 // If we found something, stop
114 TidyBag (hintIndex, bag);
115 Interlocked.Decrement (ref count);
121 public bool TryPeek (out T result)
123 result = default (T);
129 CyclicDeque<T> bag = GetBag (out hintIndex, false);
132 if (bag == null || !bag.PeekBottom (out result)) {
135 foreach (var other in staging) {
136 // Try to retrieve something based on a hint
137 ret = TryGetHint (out hintIndex) && container[hintIndex].PeekTop (out result);
139 // We fall back to testing our slot
140 if (!ret && other.Value != self)
141 ret = other.Value.PeekTop (out result);
143 // If we found something, stop
152 void AddHint (int index)
154 // We only take thread index that can be stored in 5 bits (i.e. thread ids 1-15)
158 // If cas failed then we don't retry
159 Interlocked.CompareExchange (ref hints, (int)(((uint)hs) << 4 | (uint)index), (int)hs);
162 bool TryGetHint (out int index)
164 /* Funny little thing to know, since hints is signed (because CAS has no uint overload),
165 * a shift-right operation is an arithmetic shift which might set high-order right bits
166 * to 1 instead of 0 if the number turns negative.
171 if (Interlocked.CompareExchange (ref hints, (int)(((uint)hs) >> 4), hs) == hs)
172 index = (int)(hs & 0xF);
183 public bool IsEmpty {
189 object System.Collections.ICollection.SyncRoot {
195 bool System.Collections.ICollection.IsSynchronized {
201 IEnumerator IEnumerable.GetEnumerator ()
203 return GetEnumeratorInternal ();
206 public IEnumerator<T> GetEnumerator ()
208 return GetEnumeratorInternal ();
211 IEnumerator<T> GetEnumeratorInternal ()
213 foreach (var bag in container)
214 foreach (T item in bag.Value.GetEnumerable ())
218 void System.Collections.ICollection.CopyTo (Array array, int index)
220 T[] a = array as T[];
227 public void CopyTo (T[] array, int index)
230 if (array.Length < c + index)
231 throw new InvalidOperationException ("Array is not big enough");
233 CopyTo (array, index, c);
236 void CopyTo (T[] array, int index, int num)
240 foreach (T item in this) {
248 public T[] ToArray ()
260 return Thread.CurrentThread.ManagedThreadId;
263 CyclicDeque<T> GetBag (out int index, bool createBag = true)
266 CyclicDeque<T> value;
267 if (container.TryGetValue (index, out value))
270 return createBag ? container.GetOrAdd (index, new CyclicDeque<T> ()) : null;
273 void TidyBag (int index, CyclicDeque<T> bag)
275 if (bag != null && bag.IsEmpty) {
276 if (staging.TryRemove (index, out bag) && !bag.IsEmpty)
277 staging.TryAdd (index, bag);