Chase Lev deque fences

Viewed 156

I read the article "Correct and Efficient Work-Stealing for Weak Memory Models", in which the authors give this code:

int take(Deque *q) {
    size_t b = load_explicit(&q->bottom, relaxed) - 1;
    Array *a = load_explicit(&q->array, relaxed);
    store_explicit(&q->bottom, b, relaxed);
    thread_fence(seq_cst);

    size_t t = load_explicit(&q->top, relaxed);
    int x;
    if (t <= b) {
        /* Non-empty queue. */
        x = load_explicit(&a->buffer[b % a->size], relaxed);
        if (t == b) {
            /* Single last element in queue. */
            if (!compare_exchange_strong_explicit(&q->top, &t, t + 1, seq_cst, relaxed))
                /* Failed race. */

                x = EMPTY;
            store_explicit(&q->bottom, b + 1, relaxed);
        }
    } else { /* Empty queue. */
        x = EMPTY;
        store_explicit(&q->bottom, b + 1, relaxed);
    }
    return x;
}

void push(Deque *q, int x) {
    size_t b = load_explicit(&q->bottom, relaxed);
    size_t t = load_explicit(&q->top, acquire);
    Array *a = load_explicit(&q->array, relaxed);
    if (b - t > a->size - 1) { /* Full queue. */
        resize(q);
        a = load_explicit(&q->array, relaxed);
    }
    store_explicit(&a->buffer[b % a->size], x, relaxed);
    thread_fence(release);
    store_explicit(&q->bottom, b + 1, relaxed);
}

int steal(Deque *q) {
    size_t t = load_explicit(&q->top, acquire);
    thread_fence(seq_cst);
    size_t b = load_explicit(&q->bottom, acquire);
    int x = EMPTY;
    if (t < b) {
        /* Non-empty queue. */
        Array *a = load_explicit(&q->array, consume);
        x = load_explicit(&a->buffer[t % a->size], relaxed);
        if (!compare_exchange_strong_explicit(&q->top, &t, t + 1, seq_cst, relaxed))
        /* Failed race. */
            return ABORT;
    }
    return x;
}

As we can see, in steal operation they use a seq_cst fence. Also, they use this fence in take operation. I have two questions:

  • Why do we need this fence in steal operations: can you explain some step by step example of the situation in which, without this fence in steal, we can get an undefined behavior or a race condition?
  • Why we cannot replace this fence in take operation, just by release memory store (or fence) operation (into bottom variable, aka b)?
0 Answers
Related