3 // Copyright (c) 2008 Jérémie "Garuma" Laval
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:
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
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
28 using System.Threading;
29 using System.Collections;
30 using System.Collections.Generic;
31 using System.Runtime.Serialization;
33 namespace System.Collections.Concurrent
36 [System.Diagnostics.DebuggerDisplay ("Count = {Count}")]
37 [System.Diagnostics.DebuggerTypeProxy (typeof (CollectionDebuggerView<>))]
38 public class ConcurrentStack<T> : IProducerConsumerCollection<T>, IEnumerable<T>,
39 ICollection, IEnumerable
43 public T Value = default (T);
44 public Node Next = null;
51 class NodeObjectPool : ObjectPool<Node> {
52 protected override Node Creator ()
57 static readonly NodeObjectPool pool = new NodeObjectPool ();
59 static Node ZeroOut (Node node)
61 node.Value = default(T);
66 public ConcurrentStack ()
70 public ConcurrentStack (IEnumerable<T> collection)
72 foreach (T item in collection)
76 bool IProducerConsumerCollection<T>.TryAdd (T elem)
82 public void Push (T item)
84 Node temp = pool.Take ();
88 } while (Interlocked.CompareExchange (ref head, temp, temp.Next) != temp.Next);
90 Interlocked.Increment (ref count);
93 public void PushRange (T[] items)
95 PushRange (items, 0, items.Length);
98 public void PushRange (T[] items, int startIndex, int count)
103 for (int i = startIndex; i < count; i++) {
104 Node temp = pool.Take ();
105 temp.Value = items[i];
115 } while (Interlocked.CompareExchange (ref head, insert, first.Next) != first.Next);
117 Interlocked.Add (ref count, count);
120 public bool TryPop (out T result)
127 result = default (T);
130 } while (Interlocked.CompareExchange (ref head, temp.Next, temp) != temp);
132 Interlocked.Decrement (ref count);
135 pool.Release (ZeroOut (temp));
140 public int TryPopRange (T[] items)
143 throw new ArgumentNullException ("items");
144 return TryPopRange (items, 0, items.Length);
147 public int TryPopRange (T[] items, int startIndex, int count)
150 throw new ArgumentNullException ("items");
151 if (startIndex < 0 || startIndex >= items.Length)
152 throw new ArgumentOutOfRangeException ("startIndex");
154 throw new ArgumentOutOfRangeException ("count");
155 if (startIndex + count > items.Length)
156 throw new ArgumentException ("startIndex + count is greater than the length of items.");
166 for (int j = 0; j < count; j++) {
171 } while (Interlocked.CompareExchange (ref head, end, temp) != temp);
174 for (i = startIndex; i < startIndex + count && temp != null; i++) {
175 items[i] = temp.Value;
178 pool.Release (ZeroOut (end));
180 Interlocked.Add (ref this.count, -(i - startIndex));
182 return i - startIndex;
185 public bool TryPeek (out T result)
188 if (myHead == null) {
189 result = default (T);
192 result = myHead.Value;
198 // This is not satisfactory
203 IEnumerator IEnumerable.GetEnumerator ()
205 return (IEnumerator)InternalGetEnumerator ();
208 public IEnumerator<T> GetEnumerator ()
210 return InternalGetEnumerator ();
213 IEnumerator<T> InternalGetEnumerator ()
216 if (my_head == null) {
220 yield return my_head.Value;
221 } while ((my_head = my_head.Next) != null);
225 void ICollection.CopyTo (Array array, int index)
228 throw new ArgumentNullException ("array");
230 throw new ArgumentException ("The array can't be multidimensional");
231 if (array.GetLowerBound (0) != 0)
232 throw new ArgumentException ("The array needs to be 0-based");
234 T[] dest = array as T[];
236 throw new ArgumentException ("The array cannot be cast to the collection element type", "array");
237 CopyTo (dest, index);
240 public void CopyTo (T[] array, int index)
243 throw new ArgumentNullException ("array");
245 throw new ArgumentOutOfRangeException ("index");
246 if (index >= array.Length)
247 throw new ArgumentException ("index is equals or greather than array length", "index");
249 IEnumerator<T> e = InternalGetEnumerator ();
251 while (e.MoveNext ()) {
252 if (i == array.Length - index)
253 throw new ArgumentException ("The number of elememts in the collection exceeds the capacity of array", "array");
254 array[i++] = e.Current;
258 bool ICollection.IsSynchronized {
262 bool IProducerConsumerCollection<T>.TryTake (out T item)
264 return TryPop (out item);
267 object syncRoot = new object ();
268 object ICollection.SyncRoot {
269 get { return syncRoot; }
272 public T[] ToArray ()
274 return new List<T> (this).ToArray ();
283 public bool IsEmpty {