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 const int hintThreshold = 20;
48 // We only use the add hints when number of slot is above hintThreshold
49 // so to not waste memory space and the CAS overhead
50 ConcurrentQueue<int> addHints = new ConcurrentQueue<int> ();
52 ConcurrentDictionary<int, CyclicDeque<T>> container = new ConcurrentDictionary<int, CyclicDeque<T>> ();
54 public ConcurrentBag ()
58 public ConcurrentBag (IEnumerable<T> enumerable) : this ()
60 foreach (T item in enumerable)
64 public void Add (T item)
67 CyclicDeque<T> bag = GetBag (out index);
68 bag.PushBottom (item);
71 if (container.Count > hintThreshold)
72 addHints.Enqueue (index);
74 Interlocked.Increment (ref count);
77 bool IProducerConsumerCollection<T>.TryAdd (T element)
83 public bool TryTake (out T item)
91 CyclicDeque<T> bag = GetBag (out hintIndex);
92 bool hintEnabled = container.Count > hintThreshold;
94 if (bag == null || bag.PopBottom (out item) != PopResult.Succeed) {
95 foreach (var other in container) {
96 // Try to retrieve something based on a hint
97 bool result = hintEnabled && addHints.TryDequeue (out hintIndex) && container[hintIndex].PopTop (out item) == PopResult.Succeed;
99 // We fall back to testing our slot
100 if (!result && other.Value != bag)
101 result = other.Value.PopTop (out item) == PopResult.Succeed;
103 // If we found something, stop
105 Interlocked.Decrement (ref count);
110 Interlocked.Decrement (ref count);
123 public bool IsEmpty {
129 object System.Collections.ICollection.SyncRoot {
135 bool System.Collections.ICollection.IsSynchronized {
141 IEnumerator IEnumerable.GetEnumerator ()
143 return GetEnumeratorInternal ();
146 public IEnumerator<T> GetEnumerator ()
148 return GetEnumeratorInternal ();
151 IEnumerator<T> GetEnumeratorInternal ()
153 foreach (var bag in container)
154 foreach (T item in bag.Value.GetEnumerable ())
158 void System.Collections.ICollection.CopyTo (Array array, int index)
160 T[] a = array as T[];
167 public void CopyTo (T[] array, int index)
170 if (array.Length < c + index)
171 throw new InvalidOperationException ("Array is not big enough");
173 CopyTo (array, index, c);
176 void CopyTo (T[] array, int index, int num)
180 foreach (T item in this) {
188 public T[] ToArray ()
200 return Thread.CurrentThread.ManagedThreadId;
203 CyclicDeque<T> GetBag (out int index)
206 CyclicDeque<T> value;
207 if (container.TryGetValue (index, out value))
210 return container.GetOrAdd (index, new CyclicDeque<T> ());