ConcurrentQueue.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. /*
  5. * WARNING: Auto-generated file (7/18/2012 4:47:38 PM)
  6. *
  7. * Stripped down code based on ndp\clr\src\BCL\System\Collections\Concurrent\ConcurrentQueue.cs
  8. */
  9. #if NO_CDS_COLLECTIONS
  10. #pragma warning disable 0420
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Diagnostics.Contracts;
  14. using System.Threading;
  15. namespace System.Collections.Concurrent
  16. {
  17. internal class ConcurrentQueue<T>
  18. {
  19. private volatile Segment m_head;
  20. private volatile Segment m_tail;
  21. private const int SEGMENT_SIZE = 32;
  22. public ConcurrentQueue()
  23. {
  24. m_head = m_tail = new Segment(0, this);
  25. }
  26. public bool IsEmpty
  27. {
  28. get
  29. {
  30. Segment head = m_head;
  31. if (!head.IsEmpty)
  32. //fast route 1:
  33. //if current head is not empty, then queue is not empty
  34. return false;
  35. else if (head.Next == null)
  36. //fast route 2:
  37. //if current head is empty and it's the last segment
  38. //then queue is empty
  39. return true;
  40. else
  41. //slow route:
  42. //current head is empty and it is NOT the last segment,
  43. //it means another thread is growing new segment
  44. {
  45. SpinWait spin = new SpinWait();
  46. while (head.IsEmpty)
  47. {
  48. if (head.Next == null)
  49. return true;
  50. spin.SpinOnce();
  51. head = m_head;
  52. }
  53. return false;
  54. }
  55. }
  56. }
  57. public void Enqueue(T item)
  58. {
  59. SpinWait spin = new SpinWait();
  60. while (true)
  61. {
  62. Segment tail = m_tail;
  63. if (tail.TryAppend(item))
  64. return;
  65. spin.SpinOnce();
  66. }
  67. }
  68. public bool TryDequeue(out T result)
  69. {
  70. while (!IsEmpty)
  71. {
  72. Segment head = m_head;
  73. if (head.TryRemove(out result))
  74. return true;
  75. //since method IsEmpty spins, we don't need to spin in the while loop
  76. }
  77. result = default(T);
  78. return false;
  79. }
  80. private class Segment
  81. {
  82. //we define two volatile arrays: m_array and m_state. Note that the accesses to the array items
  83. //do not get volatile treatment. But we don't need to worry about loading adjacent elements or
  84. //store/load on adjacent elements would suffer reordering.
  85. // - Two stores: these are at risk, but CLRv2 memory model guarantees store-release hence we are safe.
  86. // - Two loads: because one item from two volatile arrays are accessed, the loads of the array references
  87. // are sufficient to prevent reordering of the loads of the elements.
  88. internal volatile T[] m_array;
  89. // For each entry in m_array, the corresponding entry in m_state indicates whether this position contains
  90. // a valid value. m_state is initially all false.
  91. internal volatile VolatileBool[] m_state;
  92. //pointer to the next segment. null if the current segment is the last segment
  93. private volatile Segment m_next;
  94. //We use this zero based index to track how many segments have been created for the queue, and
  95. //to compute how many active segments are there currently.
  96. // * The number of currently active segments is : m_tail.m_index - m_head.m_index + 1;
  97. // * m_index is incremented with every Segment.Grow operation. We use Int64 type, and we can safely
  98. // assume that it never overflows. To overflow, we need to do 2^63 increments, even at a rate of 4
  99. // billion (2^32) increments per second, it takes 2^31 seconds, which is about 64 years.
  100. internal readonly long m_index;
  101. //indices of where the first and last valid values
  102. // - m_low points to the position of the next element to pop from this segment, range [0, infinity)
  103. // m_low >= SEGMENT_SIZE implies the segment is disposable
  104. // - m_high points to the position of the latest pushed element, range [-1, infinity)
  105. // m_high == -1 implies the segment is new and empty
  106. // m_high >= SEGMENT_SIZE-1 means this segment is ready to grow.
  107. // and the thread who sets m_high to SEGMENT_SIZE-1 is responsible to grow the segment
  108. // - Math.Min(m_low, SEGMENT_SIZE) > Math.Min(m_high, SEGMENT_SIZE-1) implies segment is empty
  109. // - initially m_low =0 and m_high=-1;
  110. private volatile int m_low;
  111. private volatile int m_high;
  112. private volatile ConcurrentQueue<T> m_source;
  113. internal Segment(long index, ConcurrentQueue<T> source)
  114. {
  115. m_array = new T[SEGMENT_SIZE];
  116. m_state = new VolatileBool[SEGMENT_SIZE]; //all initialized to false
  117. m_high = -1;
  118. Contract.Assert(index >= 0);
  119. m_index = index;
  120. m_source = source;
  121. }
  122. internal Segment Next
  123. {
  124. get { return m_next; }
  125. }
  126. internal bool IsEmpty
  127. {
  128. get { return (Low > High); }
  129. }
  130. internal void UnsafeAdd(T value)
  131. {
  132. Contract.Assert(m_high < SEGMENT_SIZE - 1);
  133. m_high++;
  134. m_array[m_high] = value;
  135. m_state[m_high].m_value = true;
  136. }
  137. internal Segment UnsafeGrow()
  138. {
  139. Contract.Assert(m_high >= SEGMENT_SIZE - 1);
  140. Segment newSegment = new Segment(m_index + 1, m_source); //m_index is Int64, we don't need to worry about overflow
  141. m_next = newSegment;
  142. return newSegment;
  143. }
  144. internal void Grow()
  145. {
  146. //no CAS is needed, since there is no contention (other threads are blocked, busy waiting)
  147. Segment newSegment = new Segment(m_index + 1, m_source); //m_index is Int64, we don't need to worry about overflow
  148. m_next = newSegment;
  149. Contract.Assert(m_source.m_tail == this);
  150. m_source.m_tail = m_next;
  151. }
  152. internal bool TryAppend(T value)
  153. {
  154. //quickly check if m_high is already over the boundary, if so, bail out
  155. if (m_high >= SEGMENT_SIZE - 1)
  156. {
  157. return false;
  158. }
  159. //Now we will use a CAS to increment m_high, and store the result in newhigh.
  160. //Depending on how many free spots left in this segment and how many threads are doing this Increment
  161. //at this time, the returning "newhigh" can be
  162. // 1) < SEGMENT_SIZE - 1 : we took a spot in this segment, and not the last one, just insert the value
  163. // 2) == SEGMENT_SIZE - 1 : we took the last spot, insert the value AND grow the segment
  164. // 3) > SEGMENT_SIZE - 1 : we failed to reserve a spot in this segment, we return false to
  165. // Queue.Enqueue method, telling it to try again in the next segment.
  166. int newhigh = SEGMENT_SIZE; //initial value set to be over the boundary
  167. //We need do Interlocked.Increment and value/state update in a finally block to ensure that they run
  168. //without interuption. This is to prevent anything from happening between them, and another dequeue
  169. //thread maybe spinning forever to wait for m_state[] to be true;
  170. try
  171. { }
  172. finally
  173. {
  174. newhigh = Interlocked.Increment(ref m_high);
  175. if (newhigh <= SEGMENT_SIZE - 1)
  176. {
  177. m_array[newhigh] = value;
  178. m_state[newhigh].m_value = true;
  179. }
  180. //if this thread takes up the last slot in the segment, then this thread is responsible
  181. //to grow a new segment. Calling Grow must be in the finally block too for reliability reason:
  182. //if thread abort during Grow, other threads will be left busy spinning forever.
  183. if (newhigh == SEGMENT_SIZE - 1)
  184. {
  185. Grow();
  186. }
  187. }
  188. //if newhigh <= SEGMENT_SIZE-1, it means the current thread successfully takes up a spot
  189. return newhigh <= SEGMENT_SIZE - 1;
  190. }
  191. internal bool TryRemove(out T result)
  192. {
  193. SpinWait spin = new SpinWait();
  194. int lowLocal = Low, highLocal = High;
  195. while (lowLocal <= highLocal)
  196. {
  197. //try to update m_low
  198. if (Interlocked.CompareExchange(ref m_low, lowLocal + 1, lowLocal) == lowLocal)
  199. {
  200. //if the specified value is not available (this spot is taken by a push operation,
  201. // but the value is not written into yet), then spin
  202. SpinWait spinLocal = new SpinWait();
  203. while (!m_state[lowLocal].m_value)
  204. {
  205. spinLocal.SpinOnce();
  206. }
  207. result = m_array[lowLocal];
  208. m_array[lowLocal] = default(T); //release the reference to the object.
  209. //if the current thread sets m_low to SEGMENT_SIZE, which means the current segment becomes
  210. //disposable, then this thread is responsible to dispose this segment, and reset m_head
  211. if (lowLocal + 1 >= SEGMENT_SIZE)
  212. {
  213. // Invariant: we only dispose the current m_head, not any other segment
  214. // In usual situation, disposing a segment is simply seting m_head to m_head.m_next
  215. // But there is one special case, where m_head and m_tail points to the same and ONLY
  216. //segment of the queue: Another thread A is doing Enqueue and finds that it needs to grow,
  217. //while the *current* thread is doing *this* Dequeue operation, and finds that it needs to
  218. //dispose the current (and ONLY) segment. Then we need to wait till thread A finishes its
  219. //Grow operation, this is the reason of having the following while loop
  220. spinLocal = new SpinWait();
  221. while (m_next == null)
  222. {
  223. spinLocal.SpinOnce();
  224. }
  225. Contract.Assert(m_source.m_head == this);
  226. m_source.m_head = m_next;
  227. }
  228. return true;
  229. }
  230. else
  231. {
  232. //CAS failed due to contention: spin briefly and retry
  233. spin.SpinOnce();
  234. lowLocal = Low; highLocal = High;
  235. }
  236. }//end of while
  237. result = default(T);
  238. return false;
  239. }
  240. internal bool TryPeek(out T result)
  241. {
  242. result = default(T);
  243. int lowLocal = Low;
  244. if (lowLocal > High)
  245. return false;
  246. SpinWait spin = new SpinWait();
  247. while (!m_state[lowLocal].m_value)
  248. {
  249. spin.SpinOnce();
  250. }
  251. result = m_array[lowLocal];
  252. return true;
  253. }
  254. internal int Low
  255. {
  256. get
  257. {
  258. return Math.Min(m_low, SEGMENT_SIZE);
  259. }
  260. }
  261. internal int High
  262. {
  263. get
  264. {
  265. //if m_high > SEGMENT_SIZE, it means it's out of range, we should return
  266. //SEGMENT_SIZE-1 as the logical position
  267. return Math.Min(m_high, SEGMENT_SIZE - 1);
  268. }
  269. }
  270. }
  271. }//end of class Segment
  272. struct VolatileBool
  273. {
  274. public VolatileBool(bool value)
  275. {
  276. m_value = value;
  277. }
  278. public volatile bool m_value;
  279. }
  280. }
  281. #endif