ConcurrentQueue.cs
Go to the documentation of this file.
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 
25 #if NET_4_0
26 
27 using System;
28 using System.Threading;
29 using System.Collections;
31 using System.Runtime.Serialization;
32 
33 namespace System.Collections.Concurrent
34 {
35 
36  [System.Diagnostics.DebuggerDisplay ("Count={Count}")]
37  [System.Diagnostics.DebuggerTypeProxy (typeof (CollectionDebuggerView<>))]
38  public class ConcurrentQueue<T> : IProducerConsumerCollection<T>, IEnumerable<T>, ICollection,
39  IEnumerable
40  {
41  class Node
42  {
43  public T Value;
44  public Node Next;
45  }
46 
47  Node head = new Node ();
48  Node tail;
49  int count;
50 
51  public ConcurrentQueue ()
52  {
53  tail = head;
54  }
55 
56  public ConcurrentQueue (IEnumerable<T> collection): this()
57  {
58  foreach (T item in collection)
59  Enqueue (item);
60  }
61 
62  public void Enqueue (T item)
63  {
64  Node node = new Node ();
65  node.Value = item;
66 
67  Node oldTail = null;
68  Node oldNext = null;
69 
70  bool update = false;
71  while (!update) {
72  oldTail = tail;
73  oldNext = oldTail.Next;
74 
75  // Did tail was already updated ?
76  if (tail == oldTail) {
77  if (oldNext == null) {
78  // The place is for us
79  update = AotInterlocked.CompareExchange (ref tail.Next, node, null) == null;
80  } else {
81  // another Thread already used the place so give him a hand by putting tail where it should be
82  AotInterlocked.CompareExchange (ref tail, oldNext, oldTail);
83  }
84  }
85  }
86  // 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
87  AotInterlocked.CompareExchange (ref tail, node, oldTail);
88  Interlocked.Increment (ref count);
89  }
90 
92  {
93  Enqueue (item);
94  return true;
95  }
96 
97  public bool TryDequeue (out T result)
98  {
99  result = default (T);
100  bool advanced = false;
101 
102  while (!advanced) {
103  Node oldHead = head;
104  Node oldTail = tail;
105  Node oldNext = oldHead.Next;
106 
107  if (oldHead == head) {
108  // Empty case ?
109  if (oldHead == oldTail) {
110  // This should be false then
111  if (oldNext != null) {
112  // If not then the linked list is mal formed, update tail
113  AotInterlocked.CompareExchange (ref tail, oldNext, oldTail);
114  continue;
115  }
116  result = default (T);
117  return false;
118  } else {
119  result = oldNext.Value;
120  advanced = AotInterlocked.CompareExchange (ref head, oldNext, oldHead) == oldHead;
121  }
122  }
123  }
124 
125  Interlocked.Decrement (ref count);
126 
127  return true;
128  }
129 
130  public bool TryPeek (out T result)
131  {
132  if (IsEmpty) {
133  result = default (T);
134  return false;
135  }
136 
137  Node first = head.Next;
138  result = first.Value;
139  return true;
140  }
141 
142  internal void Clear ()
143  {
144  count = 0;
145  tail = head = new Node ();
146  }
147 
148  IEnumerator IEnumerable.GetEnumerator ()
149  {
150  return (IEnumerator)InternalGetEnumerator ();
151  }
152 
153  public IEnumerator<T> GetEnumerator ()
154  {
155  return InternalGetEnumerator ();
156  }
157 
158  IEnumerator<T> InternalGetEnumerator ()
159  {
160  Node my_head = head;
161  while ((my_head = my_head.Next) != null) {
162  yield return my_head.Value;
163  }
164  }
165 
166  void ICollection.CopyTo (Array array, int index)
167  {
168  if (array == null)
169  throw new ArgumentNullException ("array");
170  if (array.Rank > 1)
171  throw new ArgumentException ("The array can't be multidimensional");
172  if (array.GetLowerBound (0) != 0)
173  throw new ArgumentException ("The array needs to be 0-based");
174 
175  T[] dest = array as T[];
176  if (dest == null)
177  throw new ArgumentException ("The array cannot be cast to the collection element type", "array");
178  CopyTo (dest, index);
179  }
180 
181  public void CopyTo (T[] array, int index)
182  {
183  if (array == null)
184  throw new ArgumentNullException ("array");
185  if (index < 0)
186  throw new ArgumentOutOfRangeException ("index");
187  if (index >= array.Length)
188  throw new ArgumentException ("index is equals or greather than array length", "index");
189 
190  IEnumerator<T> e = InternalGetEnumerator ();
191  int i = index;
192  while (e.MoveNext ()) {
193  if (i == array.Length - index)
194  throw new ArgumentException ("The number of elememts in the collection exceeds the capacity of array", "array");
195  array[i++] = e.Current;
196  }
197  }
198 
199  public T[] ToArray ()
200  {
201  return new List<T> (this).ToArray ();
202  }
203 
204  bool ICollection.IsSynchronized {
205  get { return true; }
206  }
207 
208  bool IProducerConsumerCollection<T>.TryTake (out T item)
209  {
210  return TryDequeue (out item);
211  }
212 
213  object syncRoot = new object();
214  object ICollection.SyncRoot {
215  get { return syncRoot; }
216  }
217 
218  public int Count {
219  get {
220  return count;
221  }
222  }
223 
224  public bool IsEmpty {
225  get {
226  return count == 0;
227  }
228  }
229  }
230 }
231 #endif
ConcurrentQueue(IEnumerable< T > collection)
Interlocked reference exchanges do not work with the older Mono AOT compiler so this type fudges arou...