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 #if defined(THREADED_RTS)
48 #define CASTOP(addr,old,new) ((old) == cas(((StgPtr)addr),(old),(new)))
50 /* -----------------------------------------------------------------------------
52 * -------------------------------------------------------------------------- */
54 /* internal helpers ... */
61 /* StgWord is unsigned anyway, only catch 0 */
63 barf("DeQue,roundUp2: invalid size 0 requested");
65 /* at least 1 bit set, shift up to its place */
67 rounded = rounded << 1;
68 } while (0 != (val = val>>1));
78 realsize = roundUp2(size); /* to compute modulo as a bitwise & */
80 q = (WSDeque*) stgMallocBytes(sizeof(WSDeque), /* admin fields */
82 q->elements = stgMallocBytes(realsize * sizeof(StgClosurePtr), /* dataspace */
83 "newWSDeque:data space");
86 q->topBound=0; /* read by writer, updated each time top is read */
88 q->size = realsize; /* power of 2 */
89 q->moduloSize = realsize - 1; /* n % size == n & moduloSize */
91 ASSERT_WSDEQUE_INVARIANTS(q);
95 /* -----------------------------------------------------------------------------
97 * -------------------------------------------------------------------------- */
100 freeWSDeque (WSDeque *q)
102 stgFree(q->elements);
106 /* -----------------------------------------------------------------------------
108 * popWSDeque: remove an element from the write end of the queue.
109 * Returns the removed spark, and NULL if a race is lost or the pool
112 * If only one spark is left in the pool, we synchronise with
113 * concurrently stealing threads by using cas to modify the top field.
114 * This routine should NEVER be called by a task which does not own
117 * -------------------------------------------------------------------------- */
120 popWSDeque (WSDeque *q)
122 /* also a bit tricky, has to avoid concurrent steal() calls by
123 accessing top with cas, when there is only one element left */
128 ASSERT_WSDEQUE_INVARIANTS(q);
132 // "decrement b as a test, see what happens"
136 // very important that the following read of q->top does not occur
137 // before the earlier write to q->bottom.
138 store_load_barrier();
140 t = q->top; /* using topBound would give an *upper* bound, we
141 need a lower bound. We use the real top here, but
142 can update the topBound value */
144 currSize = (long)b - (long)t;
145 if (currSize < 0) { /* was empty before decrementing b, set b
146 consistently and abort */
151 // read the element at b
152 removed = q->elements[b & q->moduloSize];
154 if (currSize > 0) { /* no danger, still elements in buffer after b-- */
155 // debugBelch("popWSDeque: t=%ld b=%ld = %ld\n", t, b, removed);
158 /* otherwise, has someone meanwhile stolen the same (last) element?
159 Check and increment top value to know */
160 if ( !(CASTOP(&(q->top),t,t+1)) ) {
161 removed = NULL; /* no success, but continue adjusting bottom */
163 q->bottom = t+1; /* anyway, empty now. Adjust bottom consistently. */
164 q->topBound = t+1; /* ...and cached top value as well */
166 ASSERT_WSDEQUE_INVARIANTS(q);
167 ASSERT(q->bottom >= q->top);
169 // debugBelch("popWSDeque: t=%ld b=%ld = %ld\n", t, b, removed);
174 /* -----------------------------------------------------------------------------
176 * -------------------------------------------------------------------------- */
179 stealWSDeque_ (WSDeque *q)
184 // Can't do this on someone else's spark pool:
185 // ASSERT_WSDEQUE_INVARIANTS(q);
187 // NB. these loads must be ordered, otherwise there is a race
188 // between steal and pop.
193 // NB. b and t are unsigned; we need a signed value for the test
194 // below, because it is possible that t > b during a
195 // concurrent popWSQueue() operation.
196 if ((long)b - (long)t <= 0 ) {
197 return NULL; /* already looks empty, abort */
200 /* now access array, see pushBottom() */
201 stolen = q->elements[t & q->moduloSize];
203 /* now decide whether we have won */
204 if ( !(CASTOP(&(q->top),t,t+1)) ) {
205 /* lost the race, someon else has changed top in the meantime */
207 } /* else: OK, top has been incremented by the cas call */
209 // debugBelch("stealWSDeque_: t=%d b=%d\n", t, b);
211 // Can't do this on someone else's spark pool:
212 // ASSERT_WSDEQUE_INVARIANTS(q);
218 stealWSDeque (WSDeque *q)
223 stolen = stealWSDeque_(q);
224 } while (stolen == NULL && !looksEmptyWSDeque(q));
229 /* -----------------------------------------------------------------------------
231 * -------------------------------------------------------------------------- */
235 /* enqueue an element. Should always succeed by resizing the array
236 (not implemented yet, silently fails in that case). */
238 pushWSDeque (WSDeque* q, void * elem)
242 StgWord sz = q->moduloSize;
244 ASSERT_WSDEQUE_INVARIANTS(q);
246 /* we try to avoid reading q->top (accessed by all) and use
247 q->topBound (accessed only by writer) instead.
248 This is why we do not just call empty(q) here.
252 if ( (StgInt)b - (StgInt)t >= (StgInt)sz ) {
253 /* NB. 1. sz == q->size - 1, thus ">="
254 2. signed comparison, it is possible that t > b
256 /* could be full, check the real top value in this case */
259 if (b - t >= sz) { /* really no space left :-( */
260 /* reallocate the array, copying the values. Concurrent steal()s
261 will in the meantime use the old one and modify only top.
262 This means: we cannot safely free the old space! Can keep it
263 on a free list internally here...
265 Potential bug in combination with steal(): if array is
266 replaced, it is unclear which one concurrent steal operations
267 use. Must read the array base address in advance in steal().
269 #if defined(DISCARD_NEW)
270 ASSERT_WSDEQUE_INVARIANTS(q);
271 return rtsFalse; // we didn't push anything
273 /* could make room by incrementing the top position here. In
274 * this case, should use CASTOP. If this fails, someone else has
275 * removed something, and new room will be available.
277 ASSERT_WSDEQUE_INVARIANTS(q);
282 q->elements[b & sz] = elem;
285 ASSERT_WSDEQUE_INVARIANTS(q);