ConcurrentBag.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. //
  2. // ConcurrentBag.cs
  3. //
  4. // Author:
  5. // Jérémie "Garuma" Laval <[email protected]>
  6. //
  7. // Copyright (c) 2009 Jérémie "Garuma" Laval
  8. //
  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:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  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
  25. // THE SOFTWARE.
  26. #if NET_4_0
  27. using System;
  28. using System.Collections;
  29. using System.Collections.Generic;
  30. using System.Diagnostics;
  31. using System.Runtime.InteropServices;
  32. using System.Threading;
  33. using System.Threading.Tasks;
  34. namespace System.Collections.Concurrent
  35. {
  36. [ComVisible (false)]
  37. [DebuggerDisplay ("Count={Count}")]
  38. [DebuggerTypeProxy (typeof (CollectionDebuggerView<>))]
  39. public class ConcurrentBag<T> : IProducerConsumerCollection<T>, IEnumerable<T>, IEnumerable
  40. {
  41. const int hintThreshold = 20;
  42. int count;
  43. // We only use the add hints when number of slot is above hintThreshold
  44. // so to not waste memory space and the CAS overhead
  45. ConcurrentQueue<int> addHints = new ConcurrentQueue<int> ();
  46. ConcurrentDictionary<int, CyclicDeque<T>> container = new ConcurrentDictionary<int, CyclicDeque<T>> ();
  47. public ConcurrentBag ()
  48. {
  49. }
  50. public ConcurrentBag (IEnumerable<T> enumerable) : this ()
  51. {
  52. foreach (T item in enumerable)
  53. Add (item);
  54. }
  55. public void Add (T item)
  56. {
  57. int index;
  58. CyclicDeque<T> bag = GetBag (out index);
  59. bag.PushBottom (item);
  60. // Cache operation ?
  61. if (container.Count > hintThreshold)
  62. addHints.Enqueue (index);
  63. Interlocked.Increment (ref count);
  64. }
  65. bool IProducerConsumerCollection<T>.TryAdd (T element)
  66. {
  67. Add (element);
  68. return true;
  69. }
  70. public bool TryTake (out T item)
  71. {
  72. item = default (T);
  73. if (count == 0)
  74. return false;
  75. int hintIndex;
  76. CyclicDeque<T> bag = GetBag (out hintIndex);
  77. bool hintEnabled = container.Count > hintThreshold;
  78. if (bag == null || bag.PopBottom (out item) != PopResult.Succeed) {
  79. foreach (var other in container) {
  80. // Try to retrieve something based on a hint
  81. bool result = hintEnabled && addHints.TryDequeue (out hintIndex) && container[hintIndex].PopTop (out item) == PopResult.Succeed;
  82. // We fall back to testing our slot
  83. if (!result)
  84. result = other.Value.PopTop (out item) == PopResult.Succeed;
  85. // If we found something, stop
  86. if (result) {
  87. Interlocked.Decrement (ref count);
  88. return true;
  89. }
  90. }
  91. } else {
  92. Interlocked.Decrement (ref count);
  93. return true;
  94. }
  95. return false;
  96. }
  97. public int Count {
  98. get {
  99. return count;
  100. }
  101. }
  102. public bool IsEmpty {
  103. get {
  104. return count == 0;
  105. }
  106. }
  107. object System.Collections.ICollection.SyncRoot {
  108. get {
  109. return this;
  110. }
  111. }
  112. bool System.Collections.ICollection.IsSynchronized {
  113. get {
  114. return true;
  115. }
  116. }
  117. IEnumerator IEnumerable.GetEnumerator ()
  118. {
  119. return GetEnumeratorInternal ();
  120. }
  121. public IEnumerator<T> GetEnumerator ()
  122. {
  123. return GetEnumeratorInternal ();
  124. }
  125. IEnumerator<T> GetEnumeratorInternal ()
  126. {
  127. foreach (var bag in container)
  128. foreach (T item in bag.Value.GetEnumerable ())
  129. yield return item;
  130. }
  131. void System.Collections.ICollection.CopyTo (Array array, int index)
  132. {
  133. T[] a = array as T[];
  134. if (a == null)
  135. return;
  136. CopyTo (a, index);
  137. }
  138. public void CopyTo (T[] array, int index)
  139. {
  140. int c = count;
  141. if (array.Length < c + index)
  142. throw new InvalidOperationException ("Array is not big enough");
  143. CopyTo (array, index, c);
  144. }
  145. void CopyTo (T[] array, int index, int num)
  146. {
  147. int i = index;
  148. foreach (T item in this) {
  149. if (i >= num)
  150. break;
  151. array[i++] = item;
  152. }
  153. }
  154. public T[] ToArray ()
  155. {
  156. int c = count;
  157. T[] temp = new T[c];
  158. CopyTo (temp, 0, c);
  159. return temp;
  160. }
  161. int GetIndex ()
  162. {
  163. return Thread.CurrentThread.ManagedThreadId;
  164. }
  165. CyclicDeque<T> GetBag (out int index)
  166. {
  167. index = GetIndex ();
  168. CyclicDeque<T> value;
  169. if (container.TryGetValue (index, out value))
  170. return value;
  171. return container.GetOrAdd (index, new CyclicDeque<T> ());
  172. }
  173. }
  174. }
  175. #endif