ConcurrentStack.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. // ConcurrentStack.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 ConcurrentStack<T> : IProducerConsumerCollection<T>, IEnumerable<T>,
  35. ICollection, IEnumerable
  36. {
  37. class Node
  38. {
  39. public T Value = default (T);
  40. public Node Next = null;
  41. }
  42. Node head = null;
  43. int count;
  44. public ConcurrentStack ()
  45. {
  46. }
  47. public ConcurrentStack (IEnumerable<T> collection)
  48. {
  49. foreach (T item in collection)
  50. Push (item);
  51. }
  52. bool IProducerConsumerCollection<T>.TryAdd (T elem)
  53. {
  54. Push (elem);
  55. return true;
  56. }
  57. public void Push (T item)
  58. {
  59. Node temp = new Node ();
  60. temp.Value = item;
  61. do {
  62. temp.Next = head;
  63. } while (Interlocked.CompareExchange (ref head, temp, temp.Next) != temp.Next);
  64. Interlocked.Increment (ref count);
  65. }
  66. public void PushRange (T[] items)
  67. {
  68. PushRange (items, 0, items.Length);
  69. }
  70. public void PushRange (T[] items, int startIndex, int count)
  71. {
  72. Node insert = null;
  73. Node first = null;
  74. for (int i = startIndex; i < count; i++) {
  75. Node temp = new Node ();
  76. temp.Value = items[i];
  77. temp.Next = insert;
  78. insert = temp;
  79. if (first == null)
  80. first = temp;
  81. }
  82. do {
  83. first.Next = head;
  84. } while (Interlocked.CompareExchange (ref head, insert, first.Next) != first.Next);
  85. Interlocked.Add (ref count, count);
  86. }
  87. public bool TryPop (out T result)
  88. {
  89. Node temp;
  90. do {
  91. temp = head;
  92. // The stak is empty
  93. if (temp == null) {
  94. result = default (T);
  95. return false;
  96. }
  97. } while (Interlocked.CompareExchange (ref head, temp.Next, temp) != temp);
  98. Interlocked.Decrement (ref count);
  99. result = temp.Value;
  100. return true;
  101. }
  102. public int TryPopRange (T[] items)
  103. {
  104. if (items == null)
  105. throw new ArgumentNullException ("items");
  106. return TryPopRange (items, 0, items.Length);
  107. }
  108. public int TryPopRange (T[] items, int startIndex, int count)
  109. {
  110. if (items == null)
  111. throw new ArgumentNullException ("items");
  112. if (startIndex < 0 || startIndex >= items.Length)
  113. throw new ArgumentOutOfRangeException ("startIndex");
  114. if (count < 0)
  115. throw new ArgumentOutOfRangeException ("count");
  116. if (startIndex + count > items.Length)
  117. throw new ArgumentException ("startIndex + count is greater than the length of items.");
  118. Node temp;
  119. Node end;
  120. do {
  121. temp = head;
  122. if (temp == null)
  123. return -1;
  124. end = temp;
  125. for (int j = 0; j < count; j++) {
  126. end = end.Next;
  127. if (end == null)
  128. break;
  129. }
  130. } while (Interlocked.CompareExchange (ref head, end, temp) != temp);
  131. int i;
  132. for (i = startIndex; i < startIndex + count && temp != null; i++) {
  133. items[i] = temp.Value;
  134. end = temp;
  135. temp = temp.Next;
  136. }
  137. Interlocked.Add (ref this.count, -(i - startIndex));
  138. return i - startIndex;
  139. }
  140. public bool TryPeek (out T result)
  141. {
  142. Node myHead = head;
  143. if (myHead == null) {
  144. result = default (T);
  145. return false;
  146. }
  147. result = myHead.Value;
  148. return true;
  149. }
  150. public void Clear ()
  151. {
  152. // This is not satisfactory
  153. count = 0;
  154. head = null;
  155. }
  156. IEnumerator IEnumerable.GetEnumerator ()
  157. {
  158. return (IEnumerator)InternalGetEnumerator ();
  159. }
  160. public IEnumerator<T> GetEnumerator ()
  161. {
  162. return InternalGetEnumerator ();
  163. }
  164. IEnumerator<T> InternalGetEnumerator ()
  165. {
  166. Node my_head = head;
  167. if (my_head == null) {
  168. yield break;
  169. } else {
  170. do {
  171. yield return my_head.Value;
  172. } while ((my_head = my_head.Next) != null);
  173. }
  174. }
  175. void ICollection.CopyTo (Array array, int index)
  176. {
  177. if (array == null)
  178. throw new ArgumentNullException ("array");
  179. if (array.Rank > 1)
  180. throw new ArgumentException ("The array can't be multidimensional");
  181. if (array.GetLowerBound (0) != 0)
  182. throw new ArgumentException ("The array needs to be 0-based");
  183. T[] dest = array as T[];
  184. if (dest == null)
  185. throw new ArgumentException ("The array cannot be cast to the collection element type", "array");
  186. CopyTo (dest, index);
  187. }
  188. public void CopyTo (T[] array, int index)
  189. {
  190. if (array == null)
  191. throw new ArgumentNullException ("array");
  192. if (index < 0)
  193. throw new ArgumentOutOfRangeException ("index");
  194. if (index >= array.Length)
  195. throw new ArgumentException ("index is equals or greather than array length", "index");
  196. IEnumerator<T> e = InternalGetEnumerator ();
  197. int i = index;
  198. while (e.MoveNext ()) {
  199. if (i == array.Length - index)
  200. throw new ArgumentException ("The number of elememts in the collection exceeds the capacity of array", "array");
  201. array[i++] = e.Current;
  202. }
  203. }
  204. bool ICollection.IsSynchronized {
  205. get { return true; }
  206. }
  207. bool IProducerConsumerCollection<T>.TryTake (out T item)
  208. {
  209. return TryPop (out item);
  210. }
  211. object syncRoot = new object ();
  212. object ICollection.SyncRoot {
  213. get { return syncRoot; }
  214. }
  215. public T[] ToArray ()
  216. {
  217. return new List<T> (this).ToArray ();
  218. }
  219. public int Count {
  220. get {
  221. return count;
  222. }
  223. }
  224. public bool IsEmpty {
  225. get {
  226. return count == 0;
  227. }
  228. }
  229. }
  230. }
  231. #endif