1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team, 2009
5 * Work-stealing Deque data structure
7 * The implementation uses Double-Ended Queues with lock-free access
8 * (thereby often called "deque") as described in
10 * D.Chase and Y.Lev, Dynamic Circular Work-Stealing Deque.
11 * SPAA'05, July 2005, Las Vegas, USA.
12 * ACM 1-58113-986-1/05/0007
14 * Author: Jost Berthold MSRC 07-09/2008
16 * The DeQue is held as a circular array with known length. Positions
17 * of top (read-end) and bottom (write-end) always increase, and the
18 * array is accessed with indices modulo array-size. While this bears
19 * the risk of overflow, we assume that (with 64 bit indices), a
20 * program must run very long to reach that point.
22 * The write end of the queue (position bottom) can only be used with
23 * mutual exclusion, i.e. by exactly one caller at a time. At this
24 * end, new items can be enqueued using pushBottom()/newSpark(), and
25 * removed using popBottom()/reclaimSpark() (the latter implying a cas
26 * synchronisation with potential concurrent readers for the case of
29 * Multiple readers can steal from the read end (position top), and
30 * are synchronised without a lock, based on a cas of the top
31 * position. One reader wins, the others return NULL for a failure.
33 * Both popWSDeque and stealWSDeque also return NULL when the queue is empty.
35 * Testing: see testsuite/tests/ghc-regress/rts/testwsdeque.c. If
36 * there's anything wrong with the deque implementation, this test
37 * will probably catch it.
39 * ---------------------------------------------------------------------------*/
44 #include "SMP.h" // for cas
46 #define CASTOP(addr,old,new) ((old) == cas(((StgPtr)addr),(old),(new)))
48 /* -----------------------------------------------------------------------------
50 * -------------------------------------------------------------------------- */
52 /* internal helpers ... */
59 /* StgWord is unsigned anyway, only catch 0 */
61 barf("DeQue,roundUp2: invalid size 0 requested");
63 /* at least 1 bit set, shift up to its place */
65 rounded = rounded << 1;
66 } while (0 != (val = val>>1));
76 realsize = roundUp2(size); /* to compute modulo as a bitwise & */
78 q = (WSDeque*) stgMallocBytes(sizeof(WSDeque), /* admin fields */
80 q->elements = stgMallocBytes(realsize * sizeof(StgClosurePtr), /* dataspace */
81 "newWSDeque:data space");
84 q->topBound=0; /* read by writer, updated each time top is read */
86 q->size = realsize; /* power of 2 */
87 q->moduloSize = realsize - 1; /* n % size == n & moduloSize */
89 ASSERT_WSDEQUE_INVARIANTS(q);
93 /* -----------------------------------------------------------------------------
95 * -------------------------------------------------------------------------- */
98 freeWSDeque (WSDeque *q)
100 stgFree(q->elements);
104 /* -----------------------------------------------------------------------------
106 * popWSDeque: remove an element from the write end of the queue.
107 * Returns the removed spark, and NULL if a race is lost or the pool
110 * If only one spark is left in the pool, we synchronise with
111 * concurrently stealing threads by using cas to modify the top field.
112 * This routine should NEVER be called by a task which does not own
115 * -------------------------------------------------------------------------- */
118 popWSDeque (WSDeque *q)
120 /* also a bit tricky, has to avoid concurrent steal() calls by
121 accessing top with cas, when there is only one element left */
126 ASSERT_WSDEQUE_INVARIANTS(q);
130 // "decrement b as a test, see what happens"
134 // very important that the following read of q->top does not occur
135 // before the earlier write to q->bottom.
136 store_load_barrier();
138 t = q->top; /* using topBound would give an *upper* bound, we
139 need a lower bound. We use the real top here, but
140 can update the topBound value */
142 currSize = (long)b - (long)t;
143 if (currSize < 0) { /* was empty before decrementing b, set b
144 consistently and abort */
149 // read the element at b
150 removed = q->elements[b & q->moduloSize];
152 if (currSize > 0) { /* no danger, still elements in buffer after b-- */
153 // debugBelch("popWSDeque: t=%ld b=%ld = %ld\n", t, b, removed);
156 /* otherwise, has someone meanwhile stolen the same (last) element?
157 Check and increment top value to know */
158 if ( !(CASTOP(&(q->top),t,t+1)) ) {
159 removed = NULL; /* no success, but continue adjusting bottom */
161 q->bottom = t+1; /* anyway, empty now. Adjust bottom consistently. */
162 q->topBound = t+1; /* ...and cached top value as well */
164 ASSERT_WSDEQUE_INVARIANTS(q);
165 ASSERT(q->bottom >= q->top);
167 // debugBelch("popWSDeque: t=%ld b=%ld = %ld\n", t, b, removed);
172 /* -----------------------------------------------------------------------------
174 * -------------------------------------------------------------------------- */
177 stealWSDeque_ (WSDeque *q)
182 // Can't do this on someone else's spark pool:
183 // ASSERT_WSDEQUE_INVARIANTS(q);
185 // NB. these loads must be ordered, otherwise there is a race
186 // between steal and pop.
191 // NB. b and t are unsigned; we need a signed value for the test
192 // below, because it is possible that t > b during a
193 // concurrent popWSQueue() operation.
194 if ((long)b - (long)t <= 0 ) {
195 return NULL; /* already looks empty, abort */
198 /* now access array, see pushBottom() */
199 stolen = q->elements[t & q->moduloSize];
201 /* now decide whether we have won */
202 if ( !(CASTOP(&(q->top),t,t+1)) ) {
203 /* lost the race, someon else has changed top in the meantime */
205 } /* else: OK, top has been incremented by the cas call */
207 // debugBelch("stealWSDeque_: t=%d b=%d\n", t, b);
209 // Can't do this on someone else's spark pool:
210 // ASSERT_WSDEQUE_INVARIANTS(q);
216 stealWSDeque (WSDeque *q)
221 stolen = stealWSDeque_(q);
222 } while (stolen == NULL && !looksEmptyWSDeque(q));
227 /* -----------------------------------------------------------------------------
229 * -------------------------------------------------------------------------- */
233 /* enqueue an element. Should always succeed by resizing the array
234 (not implemented yet, silently fails in that case). */
236 pushWSDeque (WSDeque* q, void * elem)
240 StgWord sz = q->moduloSize;
242 ASSERT_WSDEQUE_INVARIANTS(q);
244 /* we try to avoid reading q->top (accessed by all) and use
245 q->topBound (accessed only by writer) instead.
246 This is why we do not just call empty(q) here.
250 if ( (StgInt)b - (StgInt)t >= (StgInt)sz ) {
251 /* NB. 1. sz == q->size - 1, thus ">="
252 2. signed comparison, it is possible that t > b
254 /* could be full, check the real top value in this case */
257 if (b - t >= sz) { /* really no space left :-( */
258 /* reallocate the array, copying the values. Concurrent steal()s
259 will in the meantime use the old one and modify only top.
260 This means: we cannot safely free the old space! Can keep it
261 on a free list internally here...
263 Potential bug in combination with steal(): if array is
264 replaced, it is unclear which one concurrent steal operations
265 use. Must read the array base address in advance in steal().
267 #if defined(DISCARD_NEW)
268 ASSERT_WSDEQUE_INVARIANTS(q);
269 return rtsFalse; // we didn't push anything
271 /* could make room by incrementing the top position here. In
272 * this case, should use CASTOP. If this fails, someone else has
273 * removed something, and new room will be available.
275 ASSERT_WSDEQUE_INVARIANTS(q);
280 q->elements[b & sz] = elem;
283 ASSERT_WSDEQUE_INVARIANTS(q);