33 #if INSIDE_MONO_PARALLEL 34 namespace Mono.Threading.Tasks
36 namespace
System.Threading.Tasks
39 #if INSIDE_MONO_PARALLEL 42 class CyclicDeque<T> : IConcurrentDeque<T>
44 const int BaseSize = 11;
49 CircularArray<T> array =
new CircularArray<T> (BaseSize);
51 public void PushBottom (T obj)
56 long b = Interlocked.Read (ref bottom);
60 if (b - upperBound >= a.Size - 1) {
61 upperBound = Interlocked.Read (ref top);
62 a = a.Grow (b, upperBound);
67 a.segment[b % a.size] = obj;
68 Interlocked.Increment (ref bottom);
75 long b = Interlocked.Decrement (ref bottom);
77 long t = Interlocked.Read (ref top);
82 Interlocked.Add (ref bottom, t - b);
86 obj = a.segment[b % a.size];
89 Interlocked.Add (ref bottom, t + 1 - b);
91 if (Interlocked.CompareExchange (ref top, t + 1, t) != t)
97 public bool PeekBottom (out T obj)
101 long b = Interlocked.Decrement (ref bottom);
103 long t = Interlocked.Read (ref top);
109 obj = a.segment[b % a.size];
117 long t = Interlocked.Read (ref top);
118 long b = Interlocked.Read (ref bottom);
123 if (Interlocked.CompareExchange (ref top, t + 1, t) != t)
127 obj = a.segment[t % a.size];
132 internal bool PeekTop (out T obj)
136 long t = Interlocked.Read (ref top);
137 long b = Interlocked.Read (ref bottom);
143 obj = a.segment[t % a.size];
148 public IEnumerable<T> GetEnumerable ()
151 return a.GetEnumerable (bottom, ref top);
154 public bool IsEmpty {
156 long t = Interlocked.Read (ref top);
157 long b = Interlocked.Read (ref bottom);
163 internal class CircularArray<T>
165 readonly
int baseSize;
166 public readonly
int size;
167 public readonly T[] segment;
169 public CircularArray (
int baseSize)
171 this.baseSize = baseSize;
172 this.size = 1 << baseSize;
173 this.segment =
new T[size];
182 public T
this[
long index] {
184 return segment[index % size];
187 segment[index % size] = value;
191 public CircularArray<T> Grow (
long bottom,
long top)
193 var grow =
new CircularArray<T> (baseSize + 1);
195 for (
long i = top; i < bottom; i++) {
196 grow.segment[i] = segment[i % size];
202 public IEnumerable<T> GetEnumerable (
long bottom, ref
long top)
204 long instantTop = top;
205 T[] slice =
new T[bottom - instantTop];
207 for (
long i = instantTop; i < bottom; i++)
208 slice[++destIndex] = segment[i % size];
210 return RealGetEnumerable (slice, bottom, top, instantTop);
213 IEnumerable<T> RealGetEnumerable (T[] slice,
long bottom,
long realTop,
long initialTop)
215 int destIndex = (int)(realTop - initialTop - 1);
216 for (
long i = realTop; i < bottom; ++i)
217 yield
return slice[++destIndex];