ConcurrentQueue.cs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. // ConcurrentQueue.cs
  2. //
  3. // Copyright (c) 2008 Jérémie "Garuma" Laval
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. //
  24. #if NET_4_0
  25. using System;
  26. using System.Threading;
  27. using System.Collections;
  28. using System.Collections.Generic;
  29. using System.Runtime.Serialization;
  30. namespace System.Collections.Concurrent
  31. {
  32. [System.Diagnostics.DebuggerDisplay ("Count={Count}")]
  33. [System.Diagnostics.DebuggerTypeProxy (typeof (CollectionDebuggerView<>))]
  34. public class ConcurrentQueue<T> : IProducerConsumerCollection<T>, IEnumerable<T>, ICollection,
  35. IEnumerable
  36. {
  37. class Node
  38. {
  39. public T Value;
  40. public Node Next;
  41. }
  42. Node head = new Node ();
  43. Node tail;
  44. int count;
  45. public ConcurrentQueue ()
  46. {
  47. tail = head;
  48. }
  49. public ConcurrentQueue (IEnumerable<T> collection): this()
  50. {
  51. foreach (T item in collection)
  52. Enqueue (item);
  53. }
  54. public void Enqueue (T item)
  55. {
  56. Node node = new Node ();
  57. node.Value = item;
  58. Node oldTail = null;
  59. Node oldNext = null;
  60. bool update = false;
  61. while (!update) {
  62. oldTail = tail;
  63. oldNext = oldTail.Next;
  64. // Did tail was already updated ?
  65. if (tail == oldTail) {
  66. if (oldNext == null) {
  67. // The place is for us
  68. update = Interlocked.CompareExchange (ref tail.Next, node, null) == null;
  69. } else {
  70. // another Thread already used the place so give him a hand by putting tail where it should be
  71. Interlocked.CompareExchange (ref tail, oldNext, oldTail);
  72. }
  73. }
  74. }
  75. // At this point we added correctly our node, now we have to update tail. If it fails then it will be done by another thread
  76. Interlocked.CompareExchange (ref tail, node, oldTail);
  77. Interlocked.Increment (ref count);
  78. }
  79. bool IProducerConsumerCollection<T>.TryAdd (T item)
  80. {
  81. Enqueue (item);
  82. return true;
  83. }
  84. public bool TryDequeue (out T result)
  85. {
  86. result = default (T);
  87. bool advanced = false;
  88. while (!advanced) {
  89. Node oldHead = head;
  90. Node oldTail = tail;
  91. Node oldNext = oldHead.Next;
  92. if (oldHead == head) {
  93. // Empty case ?
  94. if (oldHead == oldTail) {
  95. // This should be false then
  96. if (oldNext != null) {
  97. // If not then the linked list is mal formed, update tail
  98. Interlocked.CompareExchange (ref tail, oldNext, oldTail);
  99. continue;
  100. }
  101. result = default (T);
  102. return false;
  103. } else {
  104. result = oldNext.Value;
  105. advanced = Interlocked.CompareExchange (ref head, oldNext, oldHead) == oldHead;
  106. }
  107. }
  108. }
  109. Interlocked.Decrement (ref count);
  110. return true;
  111. }
  112. public bool TryPeek (out T result)
  113. {
  114. if (IsEmpty) {
  115. result = default (T);
  116. return false;
  117. }
  118. Node first = head.Next;
  119. result = first.Value;
  120. return true;
  121. }
  122. internal void Clear ()
  123. {
  124. count = 0;
  125. tail = head = new Node ();
  126. }
  127. IEnumerator IEnumerable.GetEnumerator ()
  128. {
  129. return (IEnumerator)InternalGetEnumerator ();
  130. }
  131. public IEnumerator<T> GetEnumerator ()
  132. {
  133. return InternalGetEnumerator ();
  134. }
  135. IEnumerator<T> InternalGetEnumerator ()
  136. {
  137. Node my_head = head;
  138. while ((my_head = my_head.Next) != null) {
  139. yield return my_head.Value;
  140. }
  141. }
  142. void ICollection.CopyTo (Array array, int index)
  143. {
  144. if (array == null)
  145. throw new ArgumentNullException ("array");
  146. if (array.Rank > 1)
  147. throw new ArgumentException ("The array can't be multidimensional");
  148. if (array.GetLowerBound (0) != 0)
  149. throw new ArgumentException ("The array needs to be 0-based");
  150. T[] dest = array as T[];
  151. if (dest == null)
  152. throw new ArgumentException ("The array cannot be cast to the collection element type", "array");
  153. CopyTo (dest, index);
  154. }
  155. public void CopyTo (T[] array, int index)
  156. {
  157. if (array == null)
  158. throw new ArgumentNullException ("array");
  159. if (index < 0)
  160. throw new ArgumentOutOfRangeException ("index");
  161. if (index >= array.Length)
  162. throw new ArgumentException ("index is equals or greather than array length", "index");
  163. IEnumerator<T> e = InternalGetEnumerator ();
  164. int i = index;
  165. while (e.MoveNext ()) {
  166. if (i == array.Length - index)
  167. throw new ArgumentException ("The number of elememts in the collection exceeds the capacity of array", "array");
  168. array[i++] = e.Current;
  169. }
  170. }
  171. public T[] ToArray ()
  172. {
  173. return new List<T> (this).ToArray ();
  174. }
  175. bool ICollection.IsSynchronized {
  176. get { return true; }
  177. }
  178. bool IProducerConsumerCollection<T>.TryTake (out T item)
  179. {
  180. return TryDequeue (out item);
  181. }
  182. object syncRoot = new object();
  183. object ICollection.SyncRoot {
  184. get { return syncRoot; }
  185. }
  186. public int Count {
  187. get {
  188. return count;
  189. }
  190. }
  191. public bool IsEmpty {
  192. get {
  193. return count == 0;
  194. }
  195. }
  196. }
  197. }
  198. #endif