Debian Codegraph @

mcs/class/referencesource/mscorlib/system/collections/Concurrent/ConcurrentStack.cs

raw
1 #pragma warning disable 0420
2
3 // ==++==
4 //
5 // Copyright (c) Microsoft Corporation. All rights reserved.
6 //
7 // ==--==
8 // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
9 //
10 // ConcurrentStack.cs
11 //
12 // <OWNER>Microsoft</OWNER>
13 //
14 // A lock-free, concurrent stack primitive, and its associated debugger view type.
15 //
16 // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
17
18 using System;
19 using System.Collections;
20 using System.Collections.Generic;
21 using System.Diagnostics;
22 using System.Diagnostics.Contracts;
23 using System.Runtime.ConstrainedExecution;
24 using System.Runtime.Serialization;
25 using System.Security;
26 using System.Security.Permissions;
27 using System.Threading;
28
29 namespace System.Collections.Concurrent
30 {
31 // A stack that uses CAS operations internally to maintain thread-safety in a lock-free
32 // manner. Attempting to push or pop concurrently from the stack will not trigger waiting,
33 // although some optimistic concurrency and retry is used, possibly leading to lack of
34 // fairness and/or livelock. The stack uses spinning and backoff to add some randomization,
35 // in hopes of statistically decreasing the possibility of livelock.
36 //
37 // Note that we currently allocate a new node on every push. This avoids having to worry
38 // about potential ABA issues, since the CLR GC ensures that a memory address cannot be
39 // reused before all references to it have died.
40
41 /// <summary>
42 /// Represents a thread-safe last-in, first-out collection of objects.
43 /// </summary>
44 /// <typeparam name="T">Specifies the type of elements in the stack.</typeparam>
45 /// <remarks>
46 /// All public and protected members of <see cref="ConcurrentStack{T}"/> are thread-safe and may be used
47 /// concurrently from multiple threads.
48 /// </remarks>
49 [DebuggerDisplay("Count = {Count}")]
50 [DebuggerTypeProxy(typeof(SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView<>))]
51 [HostProtection(Synchronization = true, ExternalThreading = true)]
52 #if !FEATURE_CORECLR
53 [Serializable]
54 #endif //!FEATURE_CORECLR
55 public class ConcurrentStack<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T>
56 {
57 /// <summary>
58 /// A simple (internal) node type used to store elements of concurrent stacks and queues.
59 /// </summary>
60 private class Node
61 {
62 internal readonly T m_value; // Value of the node.
63 internal Node m_next; // Next pointer.
64
65 /// <summary>
66 /// Constructs a new node with the specified value and no next node.
67 /// </summary>
68 /// <param name="value">The value of the node.</param>
69 internal Node(T value)
70 {
71 m_value = value;
72 m_next = null;
73 }
74 }
75
76 #if !FEATURE_CORECLR
77 [NonSerialized]
78 #endif //!FEATURE_CORECLR
79 private volatile Node m_head; // The stack is a singly linked list, and only remembers the head.
80
81 #if !FEATURE_CORECLR
82 private T[] m_serializationArray; // Used for custom serialization.
83 #endif //!FEATURE_CORECLR
84
85 private const int BACKOFF_MAX_YIELDS = 8; // Arbitrary number to cap backoff.
86
87 /// <summary>
88 /// Initializes a new instance of the <see cref="ConcurrentStack{T}"/>
89 /// class.
90 /// </summary>
91 public ConcurrentStack()
92 {
93 }
94
95 /// <summary>
96 /// Initializes a new instance of the <see cref="ConcurrentStack{T}"/>
97 /// class that contains elements copied from the specified collection
98 /// </summary>
99 /// <param name="collection">The collection whose elements are copied to the new <see
100 /// cref="ConcurrentStack{T}"/>.</param>
101 /// <exception cref="T:System.ArgumentNullException">The <paramref name="collection"/> argument is
102 /// null.</exception>
103 public ConcurrentStack(IEnumerable<T> collection)
104 {
105 if (collection == null)
106 {
107 throw new ArgumentNullException("collection");
108 }
109 InitializeFromCollection(collection);
110 }
111
112 /// <summary>
113 /// Initializes the contents of the stack from an existing collection.
114 /// </summary>
115 /// <param name="collection">A collection from which to copy elements.</param>
116 private void InitializeFromCollection(IEnumerable<T> collection)
117 {
118 // We just copy the contents of the collection to our stack.
119 Node lastNode = null;
120 foreach (T element in collection)
121 {
122 Node newNode = new Node(element);
123 newNode.m_next = lastNode;
124 lastNode = newNode;
125 }
126
127 m_head = lastNode;
128 }
129
130 #if !FEATURE_CORECLR
131 /// <summary>
132 /// Get the data array to be serialized
133 /// </summary>
134 [OnSerializing]
135 private void OnSerializing(StreamingContext context)
136 {
137 // save the data into the serialization array to be saved
138 m_serializationArray = ToArray();
139 }
140
141 /// <summary>
142 /// Construct the stack from a previously seiralized one
143 /// </summary>
144 [OnDeserialized]
145 private void OnDeserialized(StreamingContext context)
146 {
147 Contract.Assert(m_serializationArray != null);
148 // Add the elements to our stack. We need to add them from head-to-tail, to
149 // preserve the original ordering of the stack before serialization.
150 Node prevNode = null;
151 Node head = null;
152 for (int i = 0; i < m_serializationArray.Length; i++)
153 {
154 Node currNode = new Node(m_serializationArray[i]);
155
156 if (prevNode == null)
157 {
158 head = currNode;
159 }
160 else
161 {
162 prevNode.m_next = currNode;
163 }
164
165 prevNode = currNode;
166 }
167
168 m_head = head;
169 m_serializationArray = null;
170 }
171 #endif //!FEATURE_CORECLR
172
173
174 /// <summary>
175 /// Gets a value that indicates whether the <see cref="ConcurrentStack{T}"/> is empty.
176 /// </summary>
177 /// <value>true if the <see cref="ConcurrentStack{T}"/> is empty; otherwise, false.</value>
178 /// <remarks>
179 /// For determining whether the collection contains any items, use of this property is recommended
180 /// rather than retrieving the number of items from the <see cref="Count"/> property and comparing it
181 /// to 0. However, as this collection is intended to be accessed concurrently, it may be the case
182 /// that another thread will modify the collection after <see cref="IsEmpty"/> returns, thus invalidating
183 /// the result.
184 /// </remarks>
185 public bool IsEmpty
186 {
187 // Checks whether the stack is empty. Clearly the answer may be out of date even prior to
188 // the function returning (i.e. if another thread concurrently adds to the stack). It does
189 // guarantee, however, that, if another thread does not mutate the stack, a subsequent call
190 // to TryPop will return true -- i.e. it will also read the stack as non-empty.
191 get { return m_head == null; }
192 }
193
194 /// <summary>
195 /// Gets the number of elements contained in the <see cref="ConcurrentStack{T}"/>.
196 /// </summary>
197 /// <value>The number of elements contained in the <see cref="ConcurrentStack{T}"/>.</value>
198 /// <remarks>
199 /// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/>
200 /// property is recommended rather than retrieving the number of items from the <see cref="Count"/>
201 /// property and comparing it to 0.
202 /// </remarks>
203 public int Count
204 {
205 // Counts the number of entries in the stack. This is an O(n) operation. The answer may be out
206 // of date before returning, but guarantees to return a count that was once valid. Conceptually,
207 // the implementation snaps a copy of the list and then counts the entries, though physically
208 // this is not what actually happens.
209 get
210 {
211 int count = 0;
212
213 // Just whip through the list and tally up the number of nodes. We rely on the fact that
214 // node next pointers are immutable after being enqueued for the first time, even as
215 // they are being dequeued. If we ever changed this (e.g. to pool nodes somehow),
216 // we'd need to revisit this implementation.
217
218 for (Node curr = m_head; curr != null; curr = curr.m_next)
219 {
220 count++; //we don't handle overflow, to be consistent with existing generic collection types in CLR
221 }
222
223 return count;
224 }
225 }
226
227
228 /// <summary>
229 /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is
230 /// synchronized with the SyncRoot.
231 /// </summary>
232 /// <value>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized
233 /// with the SyncRoot; otherwise, false. For <see cref="ConcurrentStack{T}"/>, this property always
234 /// returns false.</value>
235 bool ICollection.IsSynchronized
236 {
237 // Gets a value indicating whether access to this collection is synchronized. Always returns
238 // false. The reason is subtle. While access is in face thread safe, it's not the case that
239 // locking on the SyncRoot would have prevented concurrent pushes and pops, as this property
240 // would typically indicate; that's because we internally use CAS operations vs. true locks.
241 get { return false; }
242 }
243
244 /// <summary>
245 /// Gets an object that can be used to synchronize access to the <see
246 /// cref="T:System.Collections.ICollection"/>. This property is not supported.
247 /// </summary>
248 /// <exception cref="T:System.NotSupportedException">The SyncRoot property is not supported</exception>
249 object ICollection.SyncRoot
250 {
251 get
252 {
253 throw new NotSupportedException(Environment.GetResourceString("ConcurrentCollection_SyncRoot_NotSupported"));
254 }
255 }
256
257 /// <summary>
258 /// Removes all objects from the <see cref="ConcurrentStack{T}"/>.
259 /// </summary>
260 public void Clear()
261 {
262 // Clear the list by setting the head to null. We don't need to use an atomic
263 // operation for this: anybody who is mutating the head by pushing or popping
264 // will need to use an atomic operation to guarantee they serialize and don't
265 // overwrite our setting of the head to null.
266 m_head = null;
267 }
268
269 /// <summary>
270 /// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see
271 /// cref="T:System.Array"/>, starting at a particular
272 /// <see cref="T:System.Array"/> index.
273 /// </summary>
274 /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of
275 /// the elements copied from the
276 /// <see cref="ConcurrentStack{T}"/>. The <see cref="T:System.Array"/> must
277 /// have zero-based indexing.</param>
278 /// <param name="index">The zero-based index in <paramref name="array"/> at which copying
279 /// begins.</param>
280 /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
281 /// Visual Basic).</exception>
282 /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
283 /// zero.</exception>
284 /// <exception cref="ArgumentException">
285 /// <paramref name="array"/> is multidimensional. -or-
286 /// <paramref name="array"/> does not have zero-based indexing. -or-
287 /// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/>
288 /// -or- The number of elements in the source <see cref="T:System.Collections.ICollection"/> is
289 /// greater than the available space from <paramref name="index"/> to the end of the destination
290 /// <paramref name="array"/>. -or- The type of the source <see
291 /// cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the
292 /// destination <paramref name="array"/>.
293 /// </exception>
294 void ICollection.CopyTo(Array array, int index)
295 {
296 // Validate arguments.
297 if (array == null)
298 {
299 throw new ArgumentNullException("array");
300 }
301
302 // We must be careful not to corrupt the array, so we will first accumulate an
303 // internal list of elements that we will then copy to the array. This requires
304 // some extra allocation, but is necessary since we don't know up front whether
305 // the array is sufficiently large to hold the stack's contents.
306 ((ICollection)ToList()).CopyTo(array, index);
307 }
308
309 /// <summary>
310 /// Copies the <see cref="ConcurrentStack{T}"/> elements to an existing one-dimensional <see
311 /// cref="T:System.Array"/>, starting at the specified array index.
312 /// </summary>
313 /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of
314 /// the elements copied from the
315 /// <see cref="ConcurrentStack{T}"/>. The <see cref="T:System.Array"/> must have zero-based
316 /// indexing.</param>
317 /// <param name="index">The zero-based index in <paramref name="array"/> at which copying
318 /// begins.</param>
319 /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
320 /// Visual Basic).</exception>
321 /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
322 /// zero.</exception>
323 /// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the
324 /// length of the <paramref name="array"/>
325 /// -or- The number of elements in the source <see cref="ConcurrentStack{T}"/> is greater than the
326 /// available space from <paramref name="index"/> to the end of the destination <paramref
327 /// name="array"/>.
328 /// </exception>
329 public void CopyTo(T[] array, int index)
330 {
331 if (array == null)
332 {
333 throw new ArgumentNullException("array");
334 }
335
336 // We must be careful not to corrupt the array, so we will first accumulate an
337 // internal list of elements that we will then copy to the array. This requires
338 // some extra allocation, but is necessary since we don't know up front whether
339 // the array is sufficiently large to hold the stack's contents.
340 ToList().CopyTo(array, index);
341 }
342
343
344 /// <summary>
345 /// Inserts an object at the top of the <see cref="ConcurrentStack{T}"/>.
346 /// </summary>
347 /// <param name="item">The object to push onto the <see cref="ConcurrentStack{T}"/>. The value can be
348 /// a null reference (Nothing in Visual Basic) for reference types.
349 /// </param>
350 public void Push(T item)
351 {
352 // Pushes a node onto the front of the stack thread-safely. Internally, this simply
353 // swaps the current head pointer using a (thread safe) CAS operation to accomplish
354 // lock freedom. If the CAS fails, we add some back off to statistically decrease
355 // contention at the head, and then go back around and retry.
356
357 Node newNode = new Node(item);
358 newNode.m_next = m_head;
359 if (Interlocked.CompareExchange(ref m_head, newNode, newNode.m_next) == newNode.m_next)
360 {
361 return;
362 }
363
364 // If we failed, go to the slow path and loop around until we succeed.
365 PushCore(newNode, newNode);
366 }
367
368 /// <summary>
369 /// Inserts multiple objects at the top of the <see cref="ConcurrentStack{T}"/> atomically.
370 /// </summary>
371 /// <param name="items">The objects to push onto the <see cref="ConcurrentStack{T}"/>.</param>
372 /// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference
373 /// (Nothing in Visual Basic).</exception>
374 /// <remarks>
375 /// When adding multiple items to the stack, using PushRange is a more efficient
376 /// mechanism than using <see cref="Push"/> one item at a time. Additionally, PushRange
377 /// guarantees that all of the elements will be added atomically, meaning that no other threads will
378 /// be able to inject elements between the elements being pushed. Items at lower indices in
379 /// the <paramref name="items"/> array will be pushed before items at higher indices.
380 /// </remarks>
381 public void PushRange(T[] items)
382 {
383 if (items == null)
384 {
385 throw new ArgumentNullException("items");
386 }
387 PushRange(items, 0, items.Length);
388 }
389
390 /// <summary>
391 /// Inserts multiple objects at the top of the <see cref="ConcurrentStack{T}"/> atomically.
392 /// </summary>
393 /// <param name="items">The objects to push onto the <see cref="ConcurrentStack{T}"/>.</param>
394 /// <param name="startIndex">The zero-based offset in <paramref name="items"/> at which to begin
395 /// inserting elements onto the top of the <see cref="ConcurrentStack{T}"/>.</param>
396 /// <param name="count">The number of elements to be inserted onto the top of the <see
397 /// cref="ConcurrentStack{T}"/>.</param>
398 /// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference
399 /// (Nothing in Visual Basic).</exception>
400 /// <exception cref="ArgumentOutOfRangeException"><paramref name="startIndex"/> or <paramref
401 /// name="count"/> is negative. Or <paramref name="startIndex"/> is greater than or equal to the length
402 /// of <paramref name="items"/>.</exception>
403 /// <exception cref="ArgumentException"><paramref name="startIndex"/> + <paramref name="count"/> is
404 /// greater than the length of <paramref name="items"/>.</exception>
405 /// <remarks>
406 /// When adding multiple items to the stack, using PushRange is a more efficient
407 /// mechanism than using <see cref="Push"/> one item at a time. Additionally, PushRange
408 /// guarantees that all of the elements will be added atomically, meaning that no other threads will
409 /// be able to inject elements between the elements being pushed. Items at lower indices in the
410 /// <paramref name="items"/> array will be pushed before items at higher indices.
411 /// </remarks>
412 public void PushRange(T[] items, int startIndex, int count)
413 {
414 ValidatePushPopRangeInput(items, startIndex, count);
415
416 // No op if the count is zero
417 if (count == 0)
418 return;
419
420
421 Node head, tail;
422 head = tail = new Node(items[startIndex]);
423 for (int i = startIndex + 1; i < startIndex + count; i++)
424 {
425 Node node = new Node(items[i]);
426 node.m_next = head;
427 head = node;
428 }
429
430 tail.m_next = m_head;
431 if (Interlocked.CompareExchange(ref m_head, head, tail.m_next) == tail.m_next)
432 {
433 return;
434 }
435
436 // If we failed, go to the slow path and loop around until we succeed.
437 PushCore(head, tail);
438
439 }
440
441
442 /// <summary>
443 /// Push one or many nodes into the stack, if head and tails are equal then push one node to the stack other wise push the list between head
444 /// and tail to the stack
445 /// </summary>
446 /// <param name="head">The head pointer to the new list</param>
447 /// <param name="tail">The tail pointer to the new list</param>
448 private void PushCore(Node head, Node tail)
449 {
450 SpinWait spin = new SpinWait();
451
452 // Keep trying to CAS the exising head with the new node until we succeed.
453 do
454 {
455 spin.SpinOnce();
456 // Reread the head and link our new node.
457 tail.m_next = m_head;
458 }
459 while (Interlocked.CompareExchange(
460 ref m_head, head, tail.m_next) != tail.m_next);
461
462 #if !FEATURE_PAL && !FEATURE_CORECLR
463 if (CDSCollectionETWBCLProvider.Log.IsEnabled())
464 {
465 CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPushFailed(spin.Count);
466 }
467 #endif //!FEATURE_PAL && !FEATURE_CORECLR
468 }
469
470 /// <summary>
471 /// Local helper function to validate the Pop Push range methods input
472 /// </summary>
473 private void ValidatePushPopRangeInput(T[] items, int startIndex, int count)
474 {
475 if (items == null)
476 {
477 throw new ArgumentNullException("items");
478 }
479 if (count < 0)
480 {
481 throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ConcurrentStack_PushPopRange_CountOutOfRange"));
482 }
483 int length = items.Length;
484 if (startIndex >= length || startIndex < 0)
485 {
486 throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ConcurrentStack_PushPopRange_StartOutOfRange"));
487 }
488 if (length - count < startIndex) //instead of (startIndex + count > items.Length) to prevent overflow
489 {
490 throw new ArgumentException(Environment.GetResourceString("ConcurrentStack_PushPopRange_InvalidCount"));
491 }
492 }
493
494 /// <summary>
495 /// Attempts to add an object to the <see
496 /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>.
497 /// </summary>
498 /// <param name="item">The object to add to the <see
499 /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. The value can be a null
500 /// reference (Nothing in Visual Basic) for reference types.
501 /// </param>
502 /// <returns>true if the object was added successfully; otherwise, false.</returns>
503 /// <remarks>For <see cref="ConcurrentStack{T}"/>, this operation
504 /// will always insert the object onto the top of the <see cref="ConcurrentStack{T}"/>
505 /// and return true.</remarks>
506 bool IProducerConsumerCollection<T>.TryAdd(T item)
507 {
508 Push(item);
509 return true;
510 }
511
512 /// <summary>
513 /// Attempts to return an object from the top of the <see cref="ConcurrentStack{T}"/>
514 /// without removing it.
515 /// </summary>
516 /// <param name="result">When this method returns, <paramref name="result"/> contains an object from
517 /// the top of the <see cref="T:System.Collections.Concurrent.ConccurrentStack{T}"/> or an
518 /// unspecified value if the operation failed.</param>
519 /// <returns>true if and object was returned successfully; otherwise, false.</returns>
520 public bool TryPeek(out T result)
521 {
522 Node head = m_head;
523
524 // If the stack is empty, return false; else return the element and true.
525 if (head == null)
526 {
527 result = default(T);
528 return false;
529 }
530 else
531 {
532 result = head.m_value;
533 return true;
534 }
535 }
536
537 /// <summary>
538 /// Attempts to pop and return the object at the top of the <see cref="ConcurrentStack{T}"/>.
539 /// </summary>
540 /// <param name="result">
541 /// When this method returns, if the operation was successful, <paramref name="result"/> contains the
542 /// object removed. If no object was available to be removed, the value is unspecified.
543 /// </param>
544 /// <returns>true if an element was removed and returned from the top of the <see
545 /// cref="ConcurrentStack{T}"/>
546 /// succesfully; otherwise, false.</returns>
547 public bool TryPop(out T result)
548 {
549 Node head = m_head;
550 //stack is empty
551 if (head == null)
552 {
553 result = default(T);
554 return false;
555 }
556 if (Interlocked.CompareExchange(ref m_head, head.m_next, head) == head)
557 {
558 result = head.m_value;
559 return true;
560 }
561
562 // Fall through to the slow path.
563 return TryPopCore(out result);
564 }
565
566 /// <summary>
567 /// Attempts to pop and return multiple objects from the top of the <see cref="ConcurrentStack{T}"/>
568 /// atomically.
569 /// </summary>
570 /// <param name="items">
571 /// The <see cref="T:System.Array"/> to which objects popped from the top of the <see
572 /// cref="ConcurrentStack{T}"/> will be added.
573 /// </param>
574 /// <returns>The number of objects successfully popped from the top of the <see
575 /// cref="ConcurrentStack{T}"/> and inserted in
576 /// <paramref name="items"/>.</returns>
577 /// <exception cref="ArgumentNullException"><paramref name="items"/> is a null argument (Nothing
578 /// in Visual Basic).</exception>
579 /// <remarks>
580 /// When popping multiple items, if there is little contention on the stack, using
581 /// TryPopRange can be more efficient than using <see cref="TryPop"/>
582 /// once per item to be removed. Nodes fill the <paramref name="items"/>
583 /// with the first node to be popped at the startIndex, the second node to be popped
584 /// at startIndex + 1, and so on.
585 /// </remarks>
586 public int TryPopRange(T[] items)
587 {
588 if (items == null)
589 {
590 throw new ArgumentNullException("items");
591 }
592
593 return TryPopRange(items, 0, items.Length);
594 }
595
596 /// <summary>
597 /// Attempts to pop and return multiple objects from the top of the <see cref="ConcurrentStack{T}"/>
598 /// atomically.
599 /// </summary>
600 /// <param name="items">
601 /// The <see cref="T:System.Array"/> to which objects popped from the top of the <see
602 /// cref="ConcurrentStack{T}"/> will be added.
603 /// </param>
604 /// <param name="startIndex">The zero-based offset in <paramref name="items"/> at which to begin
605 /// inserting elements from the top of the <see cref="ConcurrentStack{T}"/>.</param>
606 /// <param name="count">The number of elements to be popped from top of the <see
607 /// cref="ConcurrentStack{T}"/> and inserted into <paramref name="items"/>.</param>
608 /// <returns>The number of objects successfully popped from the top of
609 /// the <see cref="ConcurrentStack{T}"/> and inserted in <paramref name="items"/>.</returns>
610 /// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference
611 /// (Nothing in Visual Basic).</exception>
612 /// <exception cref="ArgumentOutOfRangeException"><paramref name="startIndex"/> or <paramref
613 /// name="count"/> is negative. Or <paramref name="startIndex"/> is greater than or equal to the length
614 /// of <paramref name="items"/>.</exception>
615 /// <exception cref="ArgumentException"><paramref name="startIndex"/> + <paramref name="count"/> is
616 /// greater than the length of <paramref name="items"/>.</exception>
617 /// <remarks>
618 /// When popping multiple items, if there is little contention on the stack, using
619 /// TryPopRange can be more efficient than using <see cref="TryPop"/>
620 /// once per item to be removed. Nodes fill the <paramref name="items"/>
621 /// with the first node to be popped at the startIndex, the second node to be popped
622 /// at startIndex + 1, and so on.
623 /// </remarks>
624 public int TryPopRange(T[] items, int startIndex, int count)
625 {
626 ValidatePushPopRangeInput(items, startIndex, count);
627
628 // No op if the count is zero
629 if (count == 0)
630 return 0;
631
632 Node poppedHead;
633 int nodesCount = TryPopCore(count, out poppedHead);
634 if (nodesCount > 0)
635 {
636 CopyRemovedItems(poppedHead, items, startIndex, nodesCount);
637
638 }
639 return nodesCount;
640
641 }
642
643 /// <summary>
644 /// Local helper function to Pop an item from the stack, slow path
645 /// </summary>
646 /// <param name="result">The popped item</param>
647 /// <returns>True if succeeded, false otherwise</returns>
648 private bool TryPopCore(out T result)
649 {
650 Node poppedNode;
651
652 if (TryPopCore(1, out poppedNode) == 1)
653 {
654 result = poppedNode.m_value;
655 return true;
656 }
657
658 result = default(T);
659 return false;
660
661 }
662
663 /// <summary>
664 /// Slow path helper for TryPop. This method assumes an initial attempt to pop an element
665 /// has already occurred and failed, so it begins spinning right away.
666 /// </summary>
667 /// <param name="count">The number of items to pop.</param>
668 /// <param name="poppedHead">
669 /// When this method returns, if the pop succeeded, contains the removed object. If no object was
670 /// available to be removed, the value is unspecified. This parameter is passed uninitialized.
671 /// </param>
672 /// <returns>True if an element was removed and returned; otherwise, false.</returns>
673 private int TryPopCore(int count, out Node poppedHead)
674 {
675 SpinWait spin = new SpinWait();
676
677 // Try to CAS the head with its current next. We stop when we succeed or
678 // when we notice that the stack is empty, whichever comes first.
679 Node head;
680 Node next;
681 int backoff = 1;
682 Random r = new Random(Environment.TickCount & Int32.MaxValue); // avoid the case where TickCount could return Int32.MinValue
683 while (true)
684 {
685 head = m_head;
686 // Is the stack empty?
687 if (head == null)
688 {
689 #if !FEATURE_PAL && !FEATURE_CORECLR
690 if (count == 1 && CDSCollectionETWBCLProvider.Log.IsEnabled())
691 {
692 CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPopFailed(spin.Count);
693 }
694 #endif //!FEATURE_PAL && !FEATURE_CORECLR
695 poppedHead = null;
696 return 0;
697 }
698 next = head;
699 int nodesCount = 1;
700 for (; nodesCount < count && next.m_next != null; nodesCount++)
701 {
702 next = next.m_next;
703 }
704
705 // Try to swap the new head. If we succeed, break out of the loop.
706 if (Interlocked.CompareExchange(ref m_head, next.m_next, head) == head)
707 {
708 #if !FEATURE_PAL && !FEATURE_CORECLR
709 if (count == 1 && CDSCollectionETWBCLProvider.Log.IsEnabled())
710 {
711 CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPopFailed(spin.Count);
712 }
713 #endif //!FEATURE_PAL && !FEATURE_CORECLR
714 // Return the popped Node.
715 poppedHead = head;
716 return nodesCount;
717 }
718
719 // We failed to CAS the new head. Spin briefly and retry.
720 for (int i = 0; i < backoff; i++)
721 {
722 spin.SpinOnce();
723 }
724
725 backoff = spin.NextSpinWillYield ? r.Next(1, BACKOFF_MAX_YIELDS) : backoff * 2;
726 }
727 }
728
729
730 /// <summary>
731 /// Local helper function to copy the poped elements into a given collection
732 /// </summary>
733 /// <param name="head">The head of the list to be copied</param>
734 /// <param name="collection">The collection to place the popped items in</param>
735 /// <param name="startIndex">the beginning of index of where to place the popped items</param>
736 /// <param name="nodesCount">The number of nodes.</param>
737 private void CopyRemovedItems(Node head, T[] collection, int startIndex, int nodesCount)
738 {
739 Node current = head;
740 for (int i = startIndex; i < startIndex + nodesCount; i++)
741 {
742 collection[i] = current.m_value;
743 current = current.m_next;
744 }
745
746 }
747
748 /// <summary>
749 /// Attempts to remove and return an object from the <see
750 /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>.
751 /// </summary>
752 /// <param name="item">
753 /// When this method returns, if the operation was successful, <paramref name="item"/> contains the
754 /// object removed. If no object was available to be removed, the value is unspecified.
755 /// </param>
756 /// <returns>true if an element was removed and returned succesfully; otherwise, false.</returns>
757 /// <remarks>For <see cref="ConcurrentStack{T}"/>, this operation will attempt to pope the object at
758 /// the top of the <see cref="ConcurrentStack{T}"/>.
759 /// </remarks>
760 bool IProducerConsumerCollection<T>.TryTake(out T item)
761 {
762 return TryPop(out item);
763 }
764
765 /// <summary>
766 /// Copies the items stored in the <see cref="ConcurrentStack{T}"/> to a new array.
767 /// </summary>
768 /// <returns>A new array containing a snapshot of elements copied from the <see
769 /// cref="ConcurrentStack{T}"/>.</returns>
770 public T[] ToArray()
771 {
772 return ToList().ToArray();
773 }
774
775 /// <summary>
776 /// Returns an array containing a snapshot of the list's contents, using
777 /// the target list node as the head of a region in the list.
778 /// </summary>
779 /// <returns>An array of the list's contents.</returns>
780 private List<T> ToList()
781 {
782 List<T> list = new List<T>();
783
784 Node curr = m_head;
785 while (curr != null)
786 {
787 list.Add(curr.m_value);
788 curr = curr.m_next;
789 }
790
791 return list;
792 }
793
794 /// <summary>
795 /// Returns an enumerator that iterates through the <see cref="ConcurrentStack{T}"/>.
796 /// </summary>
797 /// <returns>An enumerator for the <see cref="ConcurrentStack{T}"/>.</returns>
798 /// <remarks>
799 /// The enumeration represents a moment-in-time snapshot of the contents
800 /// of the stack. It does not reflect any updates to the collection after
801 /// <see cref="GetEnumerator"/> was called. The enumerator is safe to use
802 /// concurrently with reads from and writes to the stack.
803 /// </remarks>
804 public IEnumerator<T> GetEnumerator()
805 {
806 // Returns an enumerator for the stack. This effectively takes a snapshot
807 // of the stack's contents at the time of the call, i.e. subsequent modifications
808 // (pushes or pops) will not be reflected in the enumerator's contents.
809
810 //If we put yield-return here, the iterator will be lazily evaluated. As a result a snapshot of
811 //the stack is not taken when GetEnumerator is initialized but when MoveNext() is first called.
812 //This is inconsistent with existing generic collections. In order to prevent it, we capture the
813 //value of m_head in a buffer and call out to a helper method
814 return GetEnumerator(m_head);
815 }
816
817 private IEnumerator<T> GetEnumerator(Node head)
818 {
819 Node current = head;
820 while (current != null)
821 {
822 yield return current.m_value;
823 current = current.m_next;
824 }
825 }
826
827 /// <summary>
828 /// Returns an enumerator that iterates through a collection.
829 /// </summary>
830 /// <returns>An <see cref="T:System.Collections.IEnumerator"/> that can be used to iterate through
831 /// the collection.</returns>
832 /// <remarks>
833 /// The enumeration represents a moment-in-time snapshot of the contents of the stack. It does not
834 /// reflect any updates to the collection after
835 /// <see cref="GetEnumerator"/> was called. The enumerator is safe to use concurrently with reads
836 /// from and writes to the stack.
837 /// </remarks>
838 IEnumerator IEnumerable.GetEnumerator()
839 {
840 return ((IEnumerable<T>)this).GetEnumerator();
841 }
842 }
843 }