ConcurrentQueue.cs 13 KB

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