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 a long
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);
69 Interlocked.Increment (ref count);
72 bool IProducerConsumerCollection<T>.TryAdd (T element)
78 public bool TryTake (out T result)
86 CyclicDeque<T> bag = GetBag (out hintIndex, false);
89 if (bag == null || bag.PopBottom (out result) != PopResult.Succeed) {
90 foreach (var other in staging) {
91 // Try to retrieve something based on a hint
92 ret = TryGetHint (out hintIndex) && (bag = container[hintIndex]).PopTop (out result) == PopResult.Succeed;
94 // We fall back to testing our slot
95 if (!ret && other.Value != bag) {
96 ret = other.Value.PopTop (out result) == PopResult.Succeed;
97 hintIndex = other.Key;
101 // If we found something, stop
108 TidyBag (hintIndex, bag);
109 Interlocked.Decrement (ref count);
115 public bool TryPeek (out T result)
117 result = default (T);
123 CyclicDeque<T> bag = GetBag (out hintIndex, false);
126 if (bag == null || !bag.PeekBottom (out result)) {
127 foreach (var other in staging) {
128 // Try to retrieve something based on a hint
129 ret = TryGetHint (out hintIndex) && container[hintIndex].PeekTop (out result);
131 // We fall back to testing our slot
132 if (!ret && other.Value != bag)
133 ret = other.Value.PeekTop (out result);
135 // If we found something, stop
144 void AddHint (int index)
146 // We only take thread index that can be stored in 5 bits (i.e. thread ids 1-15)
150 // If cas failed then we don't retry
151 Interlocked.CompareExchange (ref hints, (hs << 4) | (uint)index, hs);
154 bool TryGetHint (out int index)
159 if (Interlocked.CompareExchange (ref hints, hs >> 4, hs) == hs)
160 index = (int)(hs & 0xF);
171 public bool IsEmpty {
177 object System.Collections.ICollection.SyncRoot {
183 bool System.Collections.ICollection.IsSynchronized {
189 IEnumerator IEnumerable.GetEnumerator ()
191 return GetEnumeratorInternal ();
194 public IEnumerator<T> GetEnumerator ()
196 return GetEnumeratorInternal ();
199 IEnumerator<T> GetEnumeratorInternal ()
201 foreach (var bag in container)
202 foreach (T item in bag.Value.GetEnumerable ())
206 void System.Collections.ICollection.CopyTo (Array array, int index)
208 T[] a = array as T[];
215 public void CopyTo (T[] array, int index)
218 if (array.Length < c + index)
219 throw new InvalidOperationException ("Array is not big enough");
221 CopyTo (array, index, c);
224 void CopyTo (T[] array, int index, int num)
228 foreach (T item in this) {
236 public T[] ToArray ()
248 return Thread.CurrentThread.ManagedThreadId;
251 CyclicDeque<T> GetBag (out int index, bool createBag = true)
254 CyclicDeque<T> value;
255 if (container.TryGetValue (index, out value))
258 var bag = createBag ? container.GetOrAdd (index, new CyclicDeque<T> ()) : null;
260 staging.TryAdd (index, bag);
264 void TidyBag (int index, CyclicDeque<T> bag)
266 if (bag != null && bag.IsEmpty) {
267 if (staging.TryRemove (index, out bag) && !bag.IsEmpty)
268 staging.TryAdd (index, bag);