| 1 |
#pragma warning disable 0420 |
| 2 |
|
| 3 |
// ==++== |
| 4 |
// |
| 5 |
// Copyright (c) Microsoft Corporation. All rights reserved. |
| 6 |
// |
| 7 |
// ==--== |
| 8 |
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ |
| 9 |
// |
| 10 |
// ConcurrentQueue.cs |
| 11 |
// |
| 12 |
// <OWNER>Microsoft</OWNER> |
| 13 |
// |
| 14 |
// A lock-free, concurrent queue 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.InteropServices; |
| 25 |
using System.Runtime.Serialization; |
| 26 |
using System.Security; |
| 27 |
using System.Security.Permissions; |
| 28 |
using System.Threading; |
| 29 |
|
| 30 |
namespace System.Collections.Concurrent |
| 31 |
{ |
| 32 |
|
| 33 |
/// <summary> |
| 34 |
/// Represents a thread-safe first-in, first-out collection of objects. |
| 35 |
/// </summary> |
| 36 |
/// <typeparam name="T">Specifies the type of elements in the queue.</typeparam> |
| 37 |
/// <remarks> |
| 38 |
/// All public and protected members of <see cref="ConcurrentQueue{T}"/> are thread-safe and may be used |
| 39 |
/// concurrently from multiple threads. |
| 40 |
/// </remarks> |
| 41 |
[ComVisible(false)] |
| 42 |
[DebuggerDisplay("Count = {Count}")] |
| 43 |
[DebuggerTypeProxy(typeof(SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView<>))] |
| 44 |
[HostProtection(Synchronization = true, ExternalThreading = true)] |
| 45 |
[Serializable] |
| 46 |
public class ConcurrentQueue<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T> |
| 47 |
{ |
| 48 |
//fields of ConcurrentQueue |
| 49 |
[NonSerialized] |
| 50 |
private volatile Segment m_head; |
| 51 |
|
| 52 |
[NonSerialized] |
| 53 |
private volatile Segment m_tail; |
| 54 |
|
| 55 |
private T[] m_serializationArray; // Used for custom serialization. |
| 56 |
|
| 57 |
private const int SEGMENT_SIZE = 32; |
| 58 |
|
| 59 |
//number of snapshot takers, GetEnumerator(), ToList() and ToArray() operations take snapshot. |
| 60 |
[NonSerialized] |
| 61 |
internal volatile int m_numSnapshotTakers = 0; |
| 62 |
|
| 63 |
/// <summary> |
| 64 |
/// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> class. |
| 65 |
/// </summary> |
| 66 |
public ConcurrentQueue() |
| 67 |
{ |
| 68 |
m_head = m_tail = new Segment(0, this); |
| 69 |
} |
| 70 |
|
| 71 |
/// <summary> |
| 72 |
/// Initializes the contents of the queue from an existing collection. |
| 73 |
/// </summary> |
| 74 |
/// <param name="collection">A collection from which to copy elements.</param> |
| 75 |
private void InitializeFromCollection(IEnumerable<T> collection) |
| 76 |
{ |
| 77 |
Segment localTail = new Segment(0, this);//use this local variable to avoid the extra volatile read/write. this is safe because it is only called from ctor |
| 78 |
m_head = localTail; |
| 79 |
|
| 80 |
int index = 0; |
| 81 |
foreach (T element in collection) |
| 82 |
{ |
| 83 |
Contract.Assert(index >= 0 && index < SEGMENT_SIZE); |
| 84 |
localTail.UnsafeAdd(element); |
| 85 |
index++; |
| 86 |
|
| 87 |
if (index >= SEGMENT_SIZE) |
| 88 |
{ |
| 89 |
localTail = localTail.UnsafeGrow(); |
| 90 |
index = 0; |
| 91 |
} |
| 92 |
} |
| 93 |
|
| 94 |
m_tail = localTail; |
| 95 |
} |
| 96 |
|
| 97 |
/// <summary> |
| 98 |
/// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> |
| 99 |
/// class that contains elements copied from the specified collection |
| 100 |
/// </summary> |
| 101 |
/// <param name="collection">The collection whose elements are copied to the new <see |
| 102 |
/// cref="ConcurrentQueue{T}"/>.</param> |
| 103 |
/// <exception cref="T:System.ArgumentNullException">The <paramref name="collection"/> argument is |
| 104 |
/// null.</exception> |
| 105 |
public ConcurrentQueue(IEnumerable<T> collection) |
| 106 |
{ |
| 107 |
if (collection == null) |
| 108 |
{ |
| 109 |
throw new ArgumentNullException("collection"); |
| 110 |
} |
| 111 |
|
| 112 |
InitializeFromCollection(collection); |
| 113 |
} |
| 114 |
|
| 115 |
/// <summary> |
| 116 |
/// Get the data array to be serialized |
| 117 |
/// </summary> |
| 118 |
[OnSerializing] |
| 119 |
private void OnSerializing(StreamingContext context) |
| 120 |
{ |
| 121 |
// save the data into the serialization array to be saved |
| 122 |
m_serializationArray = ToArray(); |
| 123 |
} |
| 124 |
|
| 125 |
/// <summary> |
| 126 |
/// Construct the queue from a previously seiralized one |
| 127 |
/// </summary> |
| 128 |
[OnDeserialized] |
| 129 |
private void OnDeserialized(StreamingContext context) |
| 130 |
{ |
| 131 |
Contract.Assert(m_serializationArray != null); |
| 132 |
InitializeFromCollection(m_serializationArray); |
| 133 |
m_serializationArray = null; |
| 134 |
} |
| 135 |
|
| 136 |
/// <summary> |
| 137 |
/// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see |
| 138 |
/// cref="T:System.Array"/>, starting at a particular |
| 139 |
/// <see cref="T:System.Array"/> index. |
| 140 |
/// </summary> |
| 141 |
/// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the |
| 142 |
/// destination of the elements copied from the |
| 143 |
/// <see cref="T:System.Collections.Concurrent.ConcurrentBag"/>. The <see |
| 144 |
/// cref="T:System.Array">Array</see> must have zero-based indexing.</param> |
| 145 |
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying |
| 146 |
/// begins.</param> |
| 147 |
/// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in |
| 148 |
/// Visual Basic).</exception> |
| 149 |
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than |
| 150 |
/// zero.</exception> |
| 151 |
/// <exception cref="ArgumentException"> |
| 152 |
/// <paramref name="array"/> is multidimensional. -or- |
| 153 |
/// <paramref name="array"/> does not have zero-based indexing. -or- |
| 154 |
/// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/> |
| 155 |
/// -or- The number of elements in the source <see cref="T:System.Collections.ICollection"/> is |
| 156 |
/// greater than the available space from <paramref name="index"/> to the end of the destination |
| 157 |
/// <paramref name="array"/>. -or- The type of the source <see |
| 158 |
/// cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the |
| 159 |
/// destination <paramref name="array"/>. |
| 160 |
/// </exception> |
| 161 |
void ICollection.CopyTo(Array array, int index) |
| 162 |
{ |
| 163 |
// Validate arguments. |
| 164 |
if (array == null) |
| 165 |
{ |
| 166 |
throw new ArgumentNullException("array"); |
| 167 |
} |
| 168 |
|
| 169 |
// We must be careful not to corrupt the array, so we will first accumulate an |
| 170 |
// internal list of elements that we will then copy to the array. This requires |
| 171 |
// some extra allocation, but is necessary since we don't know up front whether |
| 172 |
// the array is sufficiently large to hold the stack's contents. |
| 173 |
((ICollection)ToList()).CopyTo(array, index); |
| 174 |
} |
| 175 |
|
| 176 |
/// <summary> |
| 177 |
/// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is |
| 178 |
/// synchronized with the SyncRoot. |
| 179 |
/// </summary> |
| 180 |
/// <value>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized |
| 181 |
/// with the SyncRoot; otherwise, false. For <see cref="ConcurrentQueue{T}"/>, this property always |
| 182 |
/// returns false.</value> |
| 183 |
bool ICollection.IsSynchronized |
| 184 |
{ |
| 185 |
// Gets a value indicating whether access to this collection is synchronized. Always returns |
| 186 |
// false. The reason is subtle. While access is in face thread safe, it's not the case that |
| 187 |
// locking on the SyncRoot would have prevented concurrent pushes and pops, as this property |
| 188 |
// would typically indicate; that's because we internally use CAS operations vs. true locks. |
| 189 |
get { return false; } |
| 190 |
} |
| 191 |
|
| 192 |
|
| 193 |
/// <summary> |
| 194 |
/// Gets an object that can be used to synchronize access to the <see |
| 195 |
/// cref="T:System.Collections.ICollection"/>. This property is not supported. |
| 196 |
/// </summary> |
| 197 |
/// <exception cref="T:System.NotSupportedException">The SyncRoot property is not supported.</exception> |
| 198 |
object ICollection.SyncRoot |
| 199 |
{ |
| 200 |
get |
| 201 |
{ |
| 202 |
throw new NotSupportedException(Environment.GetResourceString("ConcurrentCollection_SyncRoot_NotSupported")); |
| 203 |
} |
| 204 |
} |
| 205 |
|
| 206 |
/// <summary> |
| 207 |
/// Returns an enumerator that iterates through a collection. |
| 208 |
/// </summary> |
| 209 |
/// <returns>An <see cref="T:System.Collections.IEnumerator"/> that can be used to iterate through the collection.</returns> |
| 210 |
IEnumerator IEnumerable.GetEnumerator() |
| 211 |
{ |
| 212 |
return ((IEnumerable<T>)this).GetEnumerator(); |
| 213 |
} |
| 214 |
|
| 215 |
/// <summary> |
| 216 |
/// Attempts to add an object to the <see |
| 217 |
/// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. |
| 218 |
/// </summary> |
| 219 |
/// <param name="item">The object to add to the <see |
| 220 |
/// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. The value can be a null |
| 221 |
/// reference (Nothing in Visual Basic) for reference types. |
| 222 |
/// </param> |
| 223 |
/// <returns>true if the object was added successfully; otherwise, false.</returns> |
| 224 |
/// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will always add the object to the |
| 225 |
/// end of the <see cref="ConcurrentQueue{T}"/> |
| 226 |
/// and return true.</remarks> |
| 227 |
bool IProducerConsumerCollection<T>.TryAdd(T item) |
| 228 |
{ |
| 229 |
Enqueue(item); |
| 230 |
return true; |
| 231 |
} |
| 232 |
|
| 233 |
/// <summary> |
| 234 |
/// Attempts to remove and return an object from the <see |
| 235 |
/// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. |
| 236 |
/// </summary> |
| 237 |
/// <param name="item"> |
| 238 |
/// When this method returns, if the operation was successful, <paramref name="item"/> contains the |
| 239 |
/// object removed. If no object was available to be removed, the value is unspecified. |
| 240 |
/// </param> |
| 241 |
/// <returns>true if an element was removed and returned succesfully; otherwise, false.</returns> |
| 242 |
/// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will attempt to remove the object |
| 243 |
/// from the beginning of the <see cref="ConcurrentQueue{T}"/>. |
| 244 |
/// </remarks> |
| 245 |
bool IProducerConsumerCollection<T>.TryTake(out T item) |
| 246 |
{ |
| 247 |
return TryDequeue(out item); |
| 248 |
} |
| 249 |
|
| 250 |
/// <summary> |
| 251 |
/// Gets a value that indicates whether the <see cref="ConcurrentQueue{T}"/> is empty. |
| 252 |
/// </summary> |
| 253 |
/// <value>true if the <see cref="ConcurrentQueue{T}"/> is empty; otherwise, false.</value> |
| 254 |
/// <remarks> |
| 255 |
/// For determining whether the collection contains any items, use of this property is recommended |
| 256 |
/// rather than retrieving the number of items from the <see cref="Count"/> property and comparing it |
| 257 |
/// to 0. However, as this collection is intended to be accessed concurrently, it may be the case |
| 258 |
/// that another thread will modify the collection after <see cref="IsEmpty"/> returns, thus invalidating |
| 259 |
/// the result. |
| 260 |
/// </remarks> |
| 261 |
public bool IsEmpty |
| 262 |
{ |
| 263 |
get |
| 264 |
{ |
| 265 |
Segment head = m_head; |
| 266 |
if (!head.IsEmpty) |
| 267 |
//fast route 1: |
| 268 |
//if current head is not empty, then queue is not empty |
| 269 |
return false; |
| 270 |
else if (head.Next == null) |
| 271 |
//fast route 2: |
| 272 |
//if current head is empty and it's the last segment |
| 273 |
//then queue is empty |
| 274 |
return true; |
| 275 |
else |
| 276 |
//slow route: |
| 277 |
//current head is empty and it is NOT the last segment, |
| 278 |
//it means another thread is growing new segment |
| 279 |
{ |
| 280 |
SpinWait spin = new SpinWait(); |
| 281 |
while (head.IsEmpty) |
| 282 |
{ |
| 283 |
if (head.Next == null) |
| 284 |
return true; |
| 285 |
|
| 286 |
spin.SpinOnce(); |
| 287 |
head = m_head; |
| 288 |
} |
| 289 |
return false; |
| 290 |
} |
| 291 |
} |
| 292 |
} |
| 293 |
|
| 294 |
/// <summary> |
| 295 |
/// Copies the elements stored in the <see cref="ConcurrentQueue{T}"/> to a new array. |
| 296 |
/// </summary> |
| 297 |
/// <returns>A new array containing a snapshot of elements copied from the <see |
| 298 |
/// cref="ConcurrentQueue{T}"/>.</returns> |
| 299 |
public T[] ToArray() |
| 300 |
{ |
| 301 |
return ToList().ToArray(); |
| 302 |
} |
| 303 |
|
| 304 |
/// <summary> |
| 305 |
/// Copies the <see cref="ConcurrentQueue{T}"/> elements to a new <see |
| 306 |
/// cref="T:System.Collections.Generic.List{T}"/>. |
| 307 |
/// </summary> |
| 308 |
/// <returns>A new <see cref="T:System.Collections.Generic.List{T}"/> containing a snapshot of |
| 309 |
/// elements copied from the <see cref="ConcurrentQueue{T}"/>.</returns> |
| 310 |
private List<T> ToList() |
| 311 |
{ |
| 312 |
// Increments the number of active snapshot takers. This increment must happen before the snapshot is |
| 313 |
// taken. At the same time, Decrement must happen after list copying is over. Only in this way, can it |
| 314 |
// eliminate race condition when Segment.TryRemove() checks whether m_numSnapshotTakers == 0. |
| 315 |
Interlocked.Increment(ref m_numSnapshotTakers); |
| 316 |
|
| 317 |
List<T> list = new List<T>(); |
| 318 |
try |
| 319 |
{ |
| 320 |
//store head and tail positions in buffer, |
| 321 |
Segment head, tail; |
| 322 |
int headLow, tailHigh; |
| 323 |
GetHeadTailPositions(out head, out tail, out headLow, out tailHigh); |
| 324 |
|
| 325 |
if (head == tail) |
| 326 |
{ |
| 327 |
head.AddToList(list, headLow, tailHigh); |
| 328 |
} |
| 329 |
else |
| 330 |
{ |
| 331 |
head.AddToList(list, headLow, SEGMENT_SIZE - 1); |
| 332 |
Segment curr = head.Next; |
| 333 |
while (curr != tail) |
| 334 |
{ |
| 335 |
curr.AddToList(list, 0, SEGMENT_SIZE - 1); |
| 336 |
curr = curr.Next; |
| 337 |
} |
| 338 |
//Add tail segment |
| 339 |
tail.AddToList(list, 0, tailHigh); |
| 340 |
} |
| 341 |
} |
| 342 |
finally |
| 343 |
{ |
| 344 |
// This Decrement must happen after copying is over. |
| 345 |
Interlocked.Decrement(ref m_numSnapshotTakers); |
| 346 |
} |
| 347 |
return list; |
| 348 |
} |
| 349 |
|
| 350 |
/// <summary> |
| 351 |
/// Store the position of the current head and tail positions. |
| 352 |
/// </summary> |
| 353 |
/// <param name="head">return the head segment</param> |
| 354 |
/// <param name="tail">return the tail segment</param> |
| 355 |
/// <param name="headLow">return the head offset, value range [0, SEGMENT_SIZE]</param> |
| 356 |
/// <param name="tailHigh">return the tail offset, value range [-1, SEGMENT_SIZE-1]</param> |
| 357 |
private void GetHeadTailPositions(out Segment head, out Segment tail, |
| 358 |
out int headLow, out int tailHigh) |
| 359 |
{ |
| 360 |
head = m_head; |
| 361 |
tail = m_tail; |
| 362 |
headLow = head.Low; |
| 363 |
tailHigh = tail.High; |
| 364 |
SpinWait spin = new SpinWait(); |
| 365 |
|
| 366 |
//we loop until the observed values are stable and sensible. |
| 367 |
//This ensures that any update order by other methods can be tolerated. |
| 368 |
while ( |
| 369 |
//if head and tail changed, retry |
| 370 |
head != m_head || tail != m_tail |
| 371 |
//if low and high pointers, retry |
| 372 |
|| headLow != head.Low || tailHigh != tail.High |
| 373 |
//if head jumps ahead of tail because of concurrent grow and dequeue, retry |
| 374 |
|| head.m_index > tail.m_index) |
| 375 |
{ |
| 376 |
spin.SpinOnce(); |
| 377 |
head = m_head; |
| 378 |
tail = m_tail; |
| 379 |
headLow = head.Low; |
| 380 |
tailHigh = tail.High; |
| 381 |
} |
| 382 |
} |
| 383 |
|
| 384 |
|
| 385 |
/// <summary> |
| 386 |
/// Gets the number of elements contained in the <see cref="ConcurrentQueue{T}"/>. |
| 387 |
/// </summary> |
| 388 |
/// <value>The number of elements contained in the <see cref="ConcurrentQueue{T}"/>.</value> |
| 389 |
/// <remarks> |
| 390 |
/// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/> |
| 391 |
/// property is recommended rather than retrieving the number of items from the <see cref="Count"/> |
| 392 |
/// property and comparing it to 0. |
| 393 |
/// </remarks> |
| 394 |
public int Count |
| 395 |
{ |
| 396 |
get |
| 397 |
{ |
| 398 |
//store head and tail positions in buffer, |
| 399 |
Segment head, tail; |
| 400 |
int headLow, tailHigh; |
| 401 |
GetHeadTailPositions(out head, out tail, out headLow, out tailHigh); |
| 402 |
|
| 403 |
if (head == tail) |
| 404 |
{ |
| 405 |
return tailHigh - headLow + 1; |
| 406 |
} |
| 407 |
|
| 408 |
//head segment |
| 409 |
int count = SEGMENT_SIZE - headLow; |
| 410 |
|
| 411 |
//middle segment(s), if any, are full. |
| 412 |
//We don't deal with overflow to be consistent with the behavior of generic types in CLR. |
| 413 |
count += SEGMENT_SIZE * ((int)(tail.m_index - head.m_index - 1)); |
| 414 |
|
| 415 |
//tail segment |
| 416 |
count += tailHigh + 1; |
| 417 |
|
| 418 |
return count; |
| 419 |
} |
| 420 |
} |
| 421 |
|
| 422 |
|
| 423 |
/// <summary> |
| 424 |
/// Copies the <see cref="ConcurrentQueue{T}"/> elements to an existing one-dimensional <see |
| 425 |
/// cref="T:System.Array">Array</see>, starting at the specified array index. |
| 426 |
/// </summary> |
| 427 |
/// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the |
| 428 |
/// destination of the elements copied from the |
| 429 |
/// <see cref="ConcurrentQueue{T}"/>. The <see cref="T:System.Array">Array</see> must have zero-based |
| 430 |
/// indexing.</param> |
| 431 |
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying |
| 432 |
/// begins.</param> |
| 433 |
/// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in |
| 434 |
/// Visual Basic).</exception> |
| 435 |
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than |
| 436 |
/// zero.</exception> |
| 437 |
/// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the |
| 438 |
/// length of the <paramref name="array"/> |
| 439 |
/// -or- The number of elements in the source <see cref="ConcurrentQueue{T}"/> is greater than the |
| 440 |
/// available space from <paramref name="index"/> to the end of the destination <paramref |
| 441 |
/// name="array"/>. |
| 442 |
/// </exception> |
| 443 |
public void CopyTo(T[] array, int index) |
| 444 |
{ |
| 445 |
if (array == null) |
| 446 |
{ |
| 447 |
throw new ArgumentNullException("array"); |
| 448 |
} |
| 449 |
|
| 450 |
// We must be careful not to corrupt the array, so we will first accumulate an |
| 451 |
// internal list of elements that we will then copy to the array. This requires |
| 452 |
// some extra allocation, but is necessary since we don't know up front whether |
| 453 |
// the array is sufficiently large to hold the stack's contents. |
| 454 |
ToList().CopyTo(array, index); |
| 455 |
} |
| 456 |
|
| 457 |
|
| 458 |
/// <summary> |
| 459 |
/// Returns an enumerator that iterates through the <see |
| 460 |
/// cref="ConcurrentQueue{T}"/>. |
| 461 |
/// </summary> |
| 462 |
/// <returns>An enumerator for the contents of the <see |
| 463 |
/// cref="ConcurrentQueue{T}"/>.</returns> |
| 464 |
/// <remarks> |
| 465 |
/// The enumeration represents a moment-in-time snapshot of the contents |
| 466 |
/// of the queue. It does not reflect any updates to the collection after |
| 467 |
/// <see cref="GetEnumerator"/> was called. The enumerator is safe to use |
| 468 |
/// concurrently with reads from and writes to the queue. |
| 469 |
/// </remarks> |
| 470 |
public IEnumerator<T> GetEnumerator() |
| 471 |
{ |
| 472 |
// Increments the number of active snapshot takers. This increment must happen before the snapshot is |
| 473 |
// taken. At the same time, Decrement must happen after the enumeration is over. Only in this way, can it |
| 474 |
// eliminate race condition when Segment.TryRemove() checks whether m_numSnapshotTakers == 0. |
| 475 |
Interlocked.Increment(ref m_numSnapshotTakers); |
| 476 |
|
| 477 |
// Takes a snapshot of the queue. |
| 478 |
// A design flaw here: if a Thread.Abort() happens, we cannot decrement m_numSnapshotTakers. But we cannot |
| 479 |
// wrap the following with a try/finally block, otherwise the decrement will happen before the yield return |
| 480 |
// statements in the GetEnumerator (head, tail, headLow, tailHigh) method. |
| 481 |
Segment head, tail; |
| 482 |
int headLow, tailHigh; |
| 483 |
GetHeadTailPositions(out head, out tail, out headLow, out tailHigh); |
| 484 |
|
| 485 |
//If we put yield-return here, the iterator will be lazily evaluated. As a result a snapshot of |
| 486 |
// the queue is not taken when GetEnumerator is initialized but when MoveNext() is first called. |
| 487 |
// This is inconsistent with existing generic collections. In order to prevent it, we capture the |
| 488 |
// value of m_head in a buffer and call out to a helper method. |
| 489 |
//The old way of doing this was to return the ToList().GetEnumerator(), but ToList() was an |
| 490 |
// unnecessary perfomance hit. |
| 491 |
return GetEnumerator(head, tail, headLow, tailHigh); |
| 492 |
} |
| 493 |
|
| 494 |
/// <summary> |
| 495 |
/// Helper method of GetEnumerator to seperate out yield return statement, and prevent lazy evaluation. |
| 496 |
/// </summary> |
| 497 |
private IEnumerator<T> GetEnumerator(Segment head, Segment tail, int headLow, int tailHigh) |
| 498 |
{ |
| 499 |
try |
| 500 |
{ |
| 501 |
SpinWait spin = new SpinWait(); |
| 502 |
|
| 503 |
if (head == tail) |
| 504 |
{ |
| 505 |
for (int i = headLow; i <= tailHigh; i++) |
| 506 |
{ |
| 507 |
// If the position is reserved by an Enqueue operation, but the value is not written into, |
| 508 |
// spin until the value is available. |
| 509 |
spin.Reset(); |
| 510 |
while (!head.m_state[i].m_value) |
| 511 |
{ |
| 512 |
spin.SpinOnce(); |
| 513 |
} |
| 514 |
yield return head.m_array[i]; |
| 515 |
} |
| 516 |
} |
| 517 |
else |
| 518 |
{ |
| 519 |
//iterate on head segment |
| 520 |
for (int i = headLow; i < SEGMENT_SIZE; i++) |
| 521 |
{ |
| 522 |
// If the position is reserved by an Enqueue operation, but the value is not written into, |
| 523 |
// spin until the value is available. |
| 524 |
spin.Reset(); |
| 525 |
while (!head.m_state[i].m_value) |
| 526 |
{ |
| 527 |
spin.SpinOnce(); |
| 528 |
} |
| 529 |
yield return head.m_array[i]; |
| 530 |
} |
| 531 |
//iterate on middle segments |
| 532 |
Segment curr = head.Next; |
| 533 |
while (curr != tail) |
| 534 |
{ |
| 535 |
for (int i = 0; i < SEGMENT_SIZE; i++) |
| 536 |
{ |
| 537 |
// If the position is reserved by an Enqueue operation, but the value is not written into, |
| 538 |
// spin until the value is available. |
| 539 |
spin.Reset(); |
| 540 |
while (!curr.m_state[i].m_value) |
| 541 |
{ |
| 542 |
spin.SpinOnce(); |
| 543 |
} |
| 544 |
yield return curr.m_array[i]; |
| 545 |
} |
| 546 |
curr = curr.Next; |
| 547 |
} |
| 548 |
|
| 549 |
//iterate on tail segment |
| 550 |
for (int i = 0; i <= tailHigh; i++) |
| 551 |
{ |
| 552 |
// If the position is reserved by an Enqueue operation, but the value is not written into, |
| 553 |
// spin until the value is available. |
| 554 |
spin.Reset(); |
| 555 |
while (!tail.m_state[i].m_value) |
| 556 |
{ |
| 557 |
spin.SpinOnce(); |
| 558 |
} |
| 559 |
yield return tail.m_array[i]; |
| 560 |
} |
| 561 |
} |
| 562 |
} |
| 563 |
finally |
| 564 |
{ |
| 565 |
// This Decrement must happen after the enumeration is over. |
| 566 |
Interlocked.Decrement(ref m_numSnapshotTakers); |
| 567 |
} |
| 568 |
} |
| 569 |
|
| 570 |
/// <summary> |
| 571 |
/// Adds an object to the end of the <see cref="ConcurrentQueue{T}"/>. |
| 572 |
/// </summary> |
| 573 |
/// <param name="item">The object to add to the end of the <see |
| 574 |
/// cref="ConcurrentQueue{T}"/>. The value can be a null reference |
| 575 |
/// (Nothing in Visual Basic) for reference types. |
| 576 |
/// </param> |
| 577 |
public void Enqueue(T item) |
| 578 |
{ |
| 579 |
SpinWait spin = new SpinWait(); |
| 580 |
while (true) |
| 581 |
{ |
| 582 |
Segment tail = m_tail; |
| 583 |
if (tail.TryAppend(item)) |
| 584 |
return; |
| 585 |
spin.SpinOnce(); |
| 586 |
} |
| 587 |
} |
| 588 |
|
| 589 |
|
| 590 |
/// <summary> |
| 591 |
/// Attempts to remove and return the object at the beginning of the <see |
| 592 |
/// cref="ConcurrentQueue{T}"/>. |
| 593 |
/// </summary> |
| 594 |
/// <param name="result"> |
| 595 |
/// When this method returns, if the operation was successful, <paramref name="result"/> contains the |
| 596 |
/// object removed. If no object was available to be removed, the value is unspecified. |
| 597 |
/// </param> |
| 598 |
/// <returns>true if an element was removed and returned from the beggining of the <see |
| 599 |
/// cref="ConcurrentQueue{T}"/> |
| 600 |
/// succesfully; otherwise, false.</returns> |
| 601 |
public bool TryDequeue(out T result) |
| 602 |
{ |
| 603 |
while (!IsEmpty) |
| 604 |
{ |
| 605 |
Segment head = m_head; |
| 606 |
if (head.TryRemove(out result)) |
| 607 |
return true; |
| 608 |
//since method IsEmpty spins, we don't need to spin in the while loop |
| 609 |
} |
| 610 |
result = default(T); |
| 611 |
return false; |
| 612 |
} |
| 613 |
|
| 614 |
/// <summary> |
| 615 |
/// Attempts to return an object from the beginning of the <see cref="ConcurrentQueue{T}"/> |
| 616 |
/// without removing it. |
| 617 |
/// </summary> |
| 618 |
/// <param name="result">When this method returns, <paramref name="result"/> contains an object from |
| 619 |
/// the beginning of the <see cref="T:System.Collections.Concurrent.ConccurrentQueue{T}"/> or an |
| 620 |
/// unspecified value if the operation failed.</param> |
| 621 |
/// <returns>true if and object was returned successfully; otherwise, false.</returns> |
| 622 |
public bool TryPeek(out T result) |
| 623 |
{ |
| 624 |
Interlocked.Increment(ref m_numSnapshotTakers); |
| 625 |
|
| 626 |
while (!IsEmpty) |
| 627 |
{ |
| 628 |
Segment head = m_head; |
| 629 |
if (head.TryPeek(out result)) |
| 630 |
{ |
| 631 |
Interlocked.Decrement(ref m_numSnapshotTakers); |
| 632 |
return true; |
| 633 |
} |
| 634 |
//since method IsEmpty spins, we don't need to spin in the while loop |
| 635 |
} |
| 636 |
result = default(T); |
| 637 |
Interlocked.Decrement(ref m_numSnapshotTakers); |
| 638 |
return false; |
| 639 |
} |
| 640 |
|
| 641 |
|
| 642 |
/// <summary> |
| 643 |
/// private class for ConcurrentQueue. |
| 644 |
/// a queue is a linked list of small arrays, each node is called a segment. |
| 645 |
/// A segment contains an array, a pointer to the next segment, and m_low, m_high indices recording |
| 646 |
/// the first and last valid elements of the array. |
| 647 |
/// </summary> |
| 648 |
private class Segment |
| 649 |
{ |
| 650 |
//we define two volatile arrays: m_array and m_state. Note that the accesses to the array items |
| 651 |
//do not get volatile treatment. But we don't need to worry about loading adjacent elements or |
| 652 |
//store/load on adjacent elements would suffer reordering. |
| 653 |
// - Two stores: these are at risk, but CLRv2 memory model guarantees store-release hence we are safe. |
| 654 |
// - Two loads: because one item from two volatile arrays are accessed, the loads of the array references |
| 655 |
// are sufficient to prevent reordering of the loads of the elements. |
| 656 |
internal volatile T[] m_array; |
| 657 |
|
| 658 |
// For each entry in m_array, the corresponding entry in m_state indicates whether this position contains |
| 659 |
// a valid value. m_state is initially all false. |
| 660 |
internal volatile VolatileBool[] m_state; |
| 661 |
|
| 662 |
//pointer to the next segment. null if the current segment is the last segment |
| 663 |
private volatile Segment m_next; |
| 664 |
|
| 665 |
//We use this zero based index to track how many segments have been created for the queue, and |
| 666 |
//to compute how many active segments are there currently. |
| 667 |
// * The number of currently active segments is : m_tail.m_index - m_head.m_index + 1; |
| 668 |
// * m_index is incremented with every Segment.Grow operation. We use Int64 type, and we can safely |
| 669 |
// assume that it never overflows. To overflow, we need to do 2^63 increments, even at a rate of 4 |
| 670 |
// billion (2^32) increments per second, it takes 2^31 seconds, which is about 64 years. |
| 671 |
internal readonly long m_index; |
| 672 |
|
| 673 |
//indices of where the first and last valid values |
| 674 |
// - m_low points to the position of the next element to pop from this segment, range [0, infinity) |
| 675 |
// m_low >= SEGMENT_SIZE implies the segment is disposable |
| 676 |
// - m_high points to the position of the latest pushed element, range [-1, infinity) |
| 677 |
// m_high == -1 implies the segment is new and empty |
| 678 |
// m_high >= SEGMENT_SIZE-1 means this segment is ready to grow. |
| 679 |
// and the thread who sets m_high to SEGMENT_SIZE-1 is responsible to grow the segment |
| 680 |
// - Math.Min(m_low, SEGMENT_SIZE) > Math.Min(m_high, SEGMENT_SIZE-1) implies segment is empty |
| 681 |
// - initially m_low =0 and m_high=-1; |
| 682 |
private volatile int m_low; |
| 683 |
private volatile int m_high; |
| 684 |
|
| 685 |
private volatile ConcurrentQueue<T> m_source; |
| 686 |
|
| 687 |
/// <summary> |
| 688 |
/// Create and initialize a segment with the specified index. |
| 689 |
/// </summary> |
| 690 |
internal Segment(long index, ConcurrentQueue<T> source) |
| 691 |
{ |
| 692 |
m_array = new T[SEGMENT_SIZE]; |
| 693 |
m_state = new VolatileBool[SEGMENT_SIZE]; //all initialized to false |
| 694 |
m_high = -1; |
| 695 |
Contract.Assert(index >= 0); |
| 696 |
m_index = index; |
| 697 |
m_source = source; |
| 698 |
} |
| 699 |
|
| 700 |
/// <summary> |
| 701 |
/// return the next segment |
| 702 |
/// </summary> |
| 703 |
internal Segment Next |
| 704 |
{ |
| 705 |
get { return m_next; } |
| 706 |
} |
| 707 |
|
| 708 |
|
| 709 |
/// <summary> |
| 710 |
/// return true if the current segment is empty (doesn't have any element available to dequeue, |
| 711 |
/// false otherwise |
| 712 |
/// </summary> |
| 713 |
internal bool IsEmpty |
| 714 |
{ |
| 715 |
get { return (Low > High); } |
| 716 |
} |
| 717 |
|
| 718 |
/// <summary> |
| 719 |
/// Add an element to the tail of the current segment |
| 720 |
/// exclusively called by ConcurrentQueue.InitializedFromCollection |
| 721 |
/// InitializeFromCollection is responsible to guaratee that there is no index overflow, |
| 722 |
/// and there is no contention |
| 723 |
/// </summary> |
| 724 |
/// <param name="value"></param> |
| 725 |
internal void UnsafeAdd(T value) |
| 726 |
{ |
| 727 |
Contract.Assert(m_high < SEGMENT_SIZE - 1); |
| 728 |
m_high++; |
| 729 |
m_array[m_high] = value; |
| 730 |
m_state[m_high].m_value = true; |
| 731 |
} |
| 732 |
|
| 733 |
/// <summary> |
| 734 |
/// Create a new segment and append to the current one |
| 735 |
/// Does not update the m_tail pointer |
| 736 |
/// exclusively called by ConcurrentQueue.InitializedFromCollection |
| 737 |
/// InitializeFromCollection is responsible to guaratee that there is no index overflow, |
| 738 |
/// and there is no contention |
| 739 |
/// </summary> |
| 740 |
/// <returns>the reference to the new Segment</returns> |
| 741 |
internal Segment UnsafeGrow() |
| 742 |
{ |
| 743 |
Contract.Assert(m_high >= SEGMENT_SIZE - 1); |
| 744 |
Segment newSegment = new Segment(m_index + 1, m_source); //m_index is Int64, we don't need to worry about overflow |
| 745 |
m_next = newSegment; |
| 746 |
return newSegment; |
| 747 |
} |
| 748 |
|
| 749 |
/// <summary> |
| 750 |
/// Create a new segment and append to the current one |
| 751 |
/// Update the m_tail pointer |
| 752 |
/// This method is called when there is no contention |
| 753 |
/// </summary> |
| 754 |
internal void Grow() |
| 755 |
{ |
| 756 |
//no CAS is needed, since there is no contention (other threads are blocked, busy waiting) |
| 757 |
Segment newSegment = new Segment(m_index + 1, m_source); //m_index is Int64, we don't need to worry about overflow |
| 758 |
m_next = newSegment; |
| 759 |
Contract.Assert(m_source.m_tail == this); |
| 760 |
m_source.m_tail = m_next; |
| 761 |
} |
| 762 |
|
| 763 |
|
| 764 |
/// <summary> |
| 765 |
/// Try to append an element at the end of this segment. |
| 766 |
/// </summary> |
| 767 |
/// <param name="value">the element to append</param> |
| 768 |
/// <param name="tail">The tail.</param> |
| 769 |
/// <returns>true if the element is appended, false if the current segment is full</returns> |
| 770 |
/// <remarks>if appending the specified element succeeds, and after which the segment is full, |
| 771 |
/// then grow the segment</remarks> |
| 772 |
internal bool TryAppend(T value) |
| 773 |
{ |
| 774 |
//quickly check if m_high is already over the boundary, if so, bail out |
| 775 |
if (m_high >= SEGMENT_SIZE - 1) |
| 776 |
{ |
| 777 |
return false; |
| 778 |
} |
| 779 |
|
| 780 |
//Now we will use a CAS to increment m_high, and store the result in newhigh. |
| 781 |
//Depending on how many free spots left in this segment and how many threads are doing this Increment |
| 782 |
//at this time, the returning "newhigh" can be |
| 783 |
// 1) < SEGMENT_SIZE - 1 : we took a spot in this segment, and not the last one, just insert the value |
| 784 |
// 2) == SEGMENT_SIZE - 1 : we took the last spot, insert the value AND grow the segment |
| 785 |
// 3) > SEGMENT_SIZE - 1 : we failed to reserve a spot in this segment, we return false to |
| 786 |
// Queue.Enqueue method, telling it to try again in the next segment. |
| 787 |
|
| 788 |
int newhigh = SEGMENT_SIZE; //initial value set to be over the boundary |
| 789 |
|
| 790 |
//We need do Interlocked.Increment and value/state update in a finally block to ensure that they run |
| 791 |
//without interuption. This is to prevent anything from happening between them, and another dequeue |
| 792 |
//thread maybe spinning forever to wait for m_state[] to be true; |
| 793 |
try |
| 794 |
{ } |
| 795 |
finally |
| 796 |
{ |
| 797 |
newhigh = Interlocked.Increment(ref m_high); |
| 798 |
if (newhigh <= SEGMENT_SIZE - 1) |
| 799 |
{ |
| 800 |
m_array[newhigh] = value; |
| 801 |
m_state[newhigh].m_value = true; |
| 802 |
} |
| 803 |
|
| 804 |
//if this thread takes up the last slot in the segment, then this thread is responsible |
| 805 |
//to grow a new segment. Calling Grow must be in the finally block too for reliability reason: |
| 806 |
//if thread abort during Grow, other threads will be left busy spinning forever. |
| 807 |
if (newhigh == SEGMENT_SIZE - 1) |
| 808 |
{ |
| 809 |
Grow(); |
| 810 |
} |
| 811 |
} |
| 812 |
|
| 813 |
//if newhigh <= SEGMENT_SIZE-1, it means the current thread successfully takes up a spot |
| 814 |
return newhigh <= SEGMENT_SIZE - 1; |
| 815 |
} |
| 816 |
|
| 817 |
|
| 818 |
/// <summary> |
| 819 |
/// try to remove an element from the head of current segment |
| 820 |
/// </summary> |
| 821 |
/// <param name="result">The result.</param> |
| 822 |
/// <param name="head">The head.</param> |
| 823 |
/// <returns>return false only if the current segment is empty</returns> |
| 824 |
internal bool TryRemove(out T result) |
| 825 |
{ |
| 826 |
SpinWait spin = new SpinWait(); |
| 827 |
int lowLocal = Low, highLocal = High; |
| 828 |
while (lowLocal <= highLocal) |
| 829 |
{ |
| 830 |
//try to update m_low |
| 831 |
if (Interlocked.CompareExchange(ref m_low, lowLocal + 1, lowLocal) == lowLocal) |
| 832 |
{ |
| 833 |
//if the specified value is not available (this spot is taken by a push operation, |
| 834 |
// but the value is not written into yet), then spin |
| 835 |
SpinWait spinLocal = new SpinWait(); |
| 836 |
while (!m_state[lowLocal].m_value) |
| 837 |
{ |
| 838 |
spinLocal.SpinOnce(); |
| 839 |
} |
| 840 |
result = m_array[lowLocal]; |
| 841 |
|
| 842 |
// If there is no other thread taking snapshot (GetEnumerator(), ToList(), etc), reset the deleted entry to null. |
| 843 |
// It is ok if after this conditional check m_numSnapshotTakers becomes > 0, because new snapshots won't include |
| 844 |
// the deleted entry at m_array[lowLocal]. |
| 845 |
if (m_source.m_numSnapshotTakers <= 0) |
| 846 |
{ |
| 847 |
m_array[lowLocal] = default(T); //release the reference to the object. |
| 848 |
} |
| 849 |
|
| 850 |
//if the current thread sets m_low to SEGMENT_SIZE, which means the current segment becomes |
| 851 |
//disposable, then this thread is responsible to dispose this segment, and reset m_head |
| 852 |
if (lowLocal + 1 >= SEGMENT_SIZE) |
| 853 |
{ |
| 854 |
// Invariant: we only dispose the current m_head, not any other segment |
| 855 |
// In usual situation, disposing a segment is simply seting m_head to m_head.m_next |
| 856 |
// But there is one special case, where m_head and m_tail points to the same and ONLY |
| 857 |
//segment of the queue: Another thread A is doing Enqueue and finds that it needs to grow, |
| 858 |
//while the *current* thread is doing *this* Dequeue operation, and finds that it needs to |
| 859 |
//dispose the current (and ONLY) segment. Then we need to wait till thread A finishes its |
| 860 |
//Grow operation, this is the reason of having the following while loop |
| 861 |
spinLocal = new SpinWait(); |
| 862 |
while (m_next == null) |
| 863 |
{ |
| 864 |
spinLocal.SpinOnce(); |
| 865 |
} |
| 866 |
Contract.Assert(m_source.m_head == this); |
| 867 |
m_source.m_head = m_next; |
| 868 |
} |
| 869 |
return true; |
| 870 |
} |
| 871 |
else |
| 872 |
{ |
| 873 |
//CAS failed due to contention: spin briefly and retry |
| 874 |
spin.SpinOnce(); |
| 875 |
lowLocal = Low; highLocal = High; |
| 876 |
} |
| 877 |
}//end of while |
| 878 |
result = default(T); |
| 879 |
return false; |
| 880 |
} |
| 881 |
|
| 882 |
/// <summary> |
| 883 |
/// try to peek the current segment |
| 884 |
/// </summary> |
| 885 |
/// <param name="result">holds the return value of the element at the head position, |
| 886 |
/// value set to default(T) if there is no such an element</param> |
| 887 |
/// <returns>true if there are elements in the current segment, false otherwise</returns> |
| 888 |
internal bool TryPeek(out T result) |
| 889 |
{ |
| 890 |
result = default(T); |
| 891 |
int lowLocal = Low; |
| 892 |
if (lowLocal > High) |
| 893 |
return false; |
| 894 |
SpinWait spin = new SpinWait(); |
| 895 |
while (!m_state[lowLocal].m_value) |
| 896 |
{ |
| 897 |
spin.SpinOnce(); |
| 898 |
} |
| 899 |
result = m_array[lowLocal]; |
| 900 |
return true; |
| 901 |
} |
| 902 |
|
| 903 |
/// <summary> |
| 904 |
/// Adds part or all of the current segment into a List. |
| 905 |
/// </summary> |
| 906 |
/// <param name="list">the list to which to add</param> |
| 907 |
/// <param name="start">the start position</param> |
| 908 |
/// <param name="end">the end position</param> |
| 909 |
internal void AddToList(List<T> list, int start, int end) |
| 910 |
{ |
| 911 |
for (int i = start; i <= end; i++) |
| 912 |
{ |
| 913 |
SpinWait spin = new SpinWait(); |
| 914 |
while (!m_state[i].m_value) |
| 915 |
{ |
| 916 |
spin.SpinOnce(); |
| 917 |
} |
| 918 |
list.Add(m_array[i]); |
| 919 |
} |
| 920 |
} |
| 921 |
|
| 922 |
/// <summary> |
| 923 |
/// return the position of the head of the current segment |
| 924 |
/// Value range [0, SEGMENT_SIZE], if it's SEGMENT_SIZE, it means this segment is exhausted and thus empty |
| 925 |
/// </summary> |
| 926 |
internal int Low |
| 927 |
{ |
| 928 |
get |
| 929 |
{ |
| 930 |
return Math.Min(m_low, SEGMENT_SIZE); |
| 931 |
} |
| 932 |
} |
| 933 |
|
| 934 |
/// <summary> |
| 935 |
/// return the logical position of the tail of the current segment |
| 936 |
/// Value range [-1, SEGMENT_SIZE-1]. When it's -1, it means this is a new segment and has no elemnet yet |
| 937 |
/// </summary> |
| 938 |
internal int High |
| 939 |
{ |
| 940 |
get |
| 941 |
{ |
| 942 |
//if m_high > SEGMENT_SIZE, it means it's out of range, we should return |
| 943 |
//SEGMENT_SIZE-1 as the logical position |
| 944 |
return Math.Min(m_high, SEGMENT_SIZE - 1); |
| 945 |
} |
| 946 |
} |
| 947 |
|
| 948 |
} |
| 949 |
}//end of class Segment |
| 950 |
|
| 951 |
/// <summary> |
| 952 |
/// A wrapper struct for volatile bool, please note the copy of the struct it self will not be volatile |
| 953 |
/// for example this statement will not include in volatilness operation volatileBool1 = volatileBool2 the jit will copy the struct and will ignore the volatile |
| 954 |
/// </summary> |
| 955 |
struct VolatileBool |
| 956 |
{ |
| 957 |
public VolatileBool(bool value) |
| 958 |
{ |
| 959 |
m_value = value; |
| 960 |
} |
| 961 |
public volatile bool m_value; |
| 962 |
} |
| 963 |
} |