nblf-queue 0.1.12

Atomic, lock-free MPMC queues based on the nblfq algorithm
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
use alloc::boxed::Box;
use core::{marker::PhantomData, ptr::null_mut};

use crossbeam_utils::CachePadded;

use crate::{
    Growable,
    MPMCQueue,
    core::{
        AsPackedValue,
        queue::QueueCore,
        slots::{Auto, SlotType},
    },
    growable::NewSized,
    owned::buffer::BoxedBuffer,
    sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize, Ordering},
    utils::Backoff,
};

/// A lock-free non blocking queue, that may dynamically grow.
pub(crate) struct GrowableQueueCore<T, Q, S = Auto> {
    cores: [AtomicPtr<Q>; 2],
    push_epoch: CachePadded<AtomicUsize>,
    pop_epoch: CachePadded<AtomicUsize>,
    active_pushes: CachePadded<[AtomicUsize; 2]>,
    active_reads: CachePadded<[AtomicUsize; 2]>,
    is_resizing: AtomicBool,
    _slot: PhantomData<(S, T)>,
}

impl<T, Q> GrowableQueueCore<T, Q, Auto>
where
    Q: NewSized,
{
    /// Constructs a new `Queue` with capacity `size` and slot type `S`.
    /// `T` must fit into the slot type `S`
    pub(crate) fn with_slot<S>(size: usize) -> GrowableQueueCore<T, Q, S> {
        GrowableQueueCore {
            cores: [
                AtomicPtr::new(Box::into_raw(Box::new(Q::with_size(size)))),
                AtomicPtr::new(Box::into_raw(Box::new(Q::with_size(1)))),
            ],
            active_pushes: [AtomicUsize::new(0), AtomicUsize::new(0)].into(),
            active_reads: [AtomicUsize::new(0), AtomicUsize::new(0)].into(),
            push_epoch: AtomicUsize::new(0).into(),
            pop_epoch: AtomicUsize::new(0).into(),
            is_resizing: AtomicBool::new(false),
            _slot: PhantomData,
        }
    }
}

impl<T, Q, S> Drop for GrowableQueueCore<T, Q, S> {
    fn drop(&mut self) {
        let left = self.cores[0].swap(null_mut(), Ordering::Acquire);
        // Safety:
        // No concurrent drops of this ds can happen.
        // This queue was allocated in `new` or in `grow_by` with `Box::into_raw` and was not deallocated since then.
        _ = unsafe { Box::from_raw(left) };

        let right = self.cores[1].swap(null_mut(), Ordering::Acquire);
        // Safety:
        // No concurrent drops of this ds can happen.
        // This queue was allocated in `new` or in `grow_by` with `Box::into_raw` and was not deallocated since then.
        _ = unsafe { Box::from_raw(right) };
    }
}

impl<T, Q, S> Growable for GrowableQueueCore<T, Q, S>
where
    Q: NewSized + MPMCQueue<Item = T>,
{
    fn grow_by(&self, by: usize) -> bool {
        let pop_epoch = self.pop_epoch.load(Ordering::Acquire);
        let push_epoch = self.push_epoch.load(Ordering::Acquire);

        if pop_epoch != push_epoch {
            return false;
        }

        if self.active_reads[(push_epoch + 1) % 2].load(Ordering::Acquire) != 0 {
            // could happen if some thread started reading before pop_epoch got updated
            return false;
        }

        if self.is_resizing.swap(true, Ordering::AcqRel) {
            return false;
        }

        if self.push_epoch.load(Ordering::Acquire) != push_epoch {
            // could happen if an entire resize happens between load and this check
            self.is_resizing.store(false, Ordering::Release);
            return false;
        }

        // at this poitn we know that
        // a) no concurrent resize is happening
        // b) since pop_epoch == push_epoch the old queue is empty.
        // c) since pop_epoch == push_epoch AND active_reads == 0, we know that active_reads is STILL 0, becasue noone will acces the stale queue

        let old_idx = (push_epoch + 1) % 2;
        let mut backoff = Backoff::new();

        while self.active_reads[old_idx].load(Ordering::Acquire) != 0 {
            backoff.backoff();
        }

        debug_assert_eq!(
            self.active_pushes[(push_epoch + 1) % 2].load(Ordering::SeqCst),
            0
        );

        let new_queue = Box::into_raw(Box::new(Q::with_size(self.capacity() + by)));

        // Safety:
        // since pop_epoch == push_epoch all concurrent threads acces the queue at push_epoch % 2.
        // pop ensures that no pushes are in flight to the old queue anymore and that it is empty. We can safely drop it.
        let old_queue = self.cores[(push_epoch + 1) % 2].swap(new_queue, Ordering::AcqRel);
        self.push_epoch.fetch_add(1, Ordering::Release);

        // Safety:
        // old_queue was ocnstucted from a Bos::into_raw and is dropped only once, as ensured by epoch guards
        let q = unsafe { Box::from_raw(old_queue) };

        debug_assert!(q.pop().is_none());

        self.is_resizing.store(false, Ordering::Release);
        true
    }
}

impl<T, Q, S> GrowableQueueCore<T, Q, S> {
    fn get_queue(&self, epoch: usize) -> &Q {
        let queue = self.cores[epoch % 2].load(Ordering::Acquire);
        // Safety:
        // It is guranteed by `grow_by` that no concurrent mutable access can happen to any queue in cores.
        // It is safe to access it concurrently via shared ref, as long as queue core is Sync.
        unsafe { &*queue }
    }

    fn register_reader(&self, target_epoch: usize) -> bool {
        self.active_reads[target_epoch % 2].fetch_add(1, Ordering::Release);

        let current_push = self.push_epoch.load(Ordering::SeqCst);
        let current_pop = self.pop_epoch.load(Ordering::SeqCst);

        // It is safe to read if the target epoch is still structurally active
        if target_epoch != current_push && target_epoch != current_pop {
            self.deregister_reader(target_epoch);
            return false;
        }
        true
    }

    fn deregister_reader(&self, epoch: usize) {
        self.active_reads[epoch % 2].fetch_sub(1, Ordering::Release);
    }
}

impl<T, Q, S> MPMCQueue for GrowableQueueCore<T, Q, S>
where
    Q: MPMCQueue<Item = T>,
{
    type Item = T;

    fn push(&self, item: Self::Item) -> Result<(), Self::Item> {
        loop {
            let push_epoch = self.push_epoch.load(Ordering::Acquire);
            self.active_pushes[push_epoch % 2].fetch_add(1, Ordering::Release);

            if self.push_epoch.load(Ordering::SeqCst) == push_epoch {
                let r = self.get_queue(push_epoch).push(item);

                self.active_pushes[push_epoch % 2].fetch_sub(1, Ordering::Release);
                return r;
            }
            self.active_pushes[push_epoch % 2].fetch_sub(1, Ordering::Release);
        }
    }

    fn pop(&self) -> Option<Self::Item> {
        loop {
            let pop_epoch = self.pop_epoch.load(Ordering::Acquire);
            let push_epoch = self.push_epoch.load(Ordering::Acquire);

            if pop_epoch != push_epoch {
                // drain old buffer

                if !self.register_reader(pop_epoch) {
                    continue;
                }

                // it is safe to call get_queue on pop_epoch here, since no resize can happen while we have not updated pop_epoch and reads on this epoch are happening
                let item = self.get_queue(pop_epoch).pop();

                self.deregister_reader(pop_epoch);

                if item.is_some() {
                    return item;
                }

                if self.active_pushes[pop_epoch % 2].load(Ordering::Acquire) == 0 {
                    if !self.register_reader(pop_epoch) {
                        continue;
                    }

                    let final_item = self.get_queue(pop_epoch).pop();

                    self.deregister_reader(pop_epoch);

                    if final_item.is_some() {
                        return final_item;
                    }

                    _ = self.pop_epoch.compare_exchange_weak(
                        pop_epoch,
                        pop_epoch + 1,
                        Ordering::AcqRel,
                        Ordering::Relaxed,
                    );
                }

                continue;
            }

            if !self.register_reader(push_epoch) {
                continue;
            }

            let item = self.get_queue(push_epoch).pop();

            self.deregister_reader(push_epoch);

            return item;
        }
    }

    fn capacity(&self) -> usize {
        // the capacity of the currently active queue, i.e. the number of elements that can be pushed directly after resize
        loop {
            let push_epoch = self.push_epoch.load(Ordering::Acquire);
            if !self.register_reader(push_epoch) {
                continue;
            }
            let cap = self.get_queue(push_epoch).capacity();
            self.deregister_reader(push_epoch);
            return cap;
        }
    }

    fn len(&self) -> usize {
        // the total elements in the queue. Note that len can be > capacity.
        loop {
            let push_epoch = self.push_epoch.load(Ordering::Acquire);
            if !self.register_reader(push_epoch) {
                continue;
            }

            let pop_epoch = self.pop_epoch.load(Ordering::Acquire);
            let pop_len = if pop_epoch != push_epoch {
                if !self.register_reader(pop_epoch) {
                    self.deregister_reader(push_epoch);
                    continue;
                }

                let pop_len = self.get_queue(pop_epoch).len();
                self.deregister_reader(pop_epoch);
                pop_len
            } else {
                0
            };

            let len = self.get_queue(push_epoch).len() + pop_len;
            self.deregister_reader(push_epoch);
            return len;
        }
    }

    fn is_empty(&self) -> bool {
        // the queue is empty if pop() returns None
        loop {
            let push_epoch = self.push_epoch.load(Ordering::Acquire);
            if !self.register_reader(push_epoch) {
                continue;
            }

            let pop_epoch = self.pop_epoch.load(Ordering::Acquire);
            let pop_is_empty = if pop_epoch != push_epoch {
                if !self.register_reader(pop_epoch) {
                    self.deregister_reader(push_epoch);
                    continue;
                }

                let pop_is_empty = self.get_queue(pop_epoch).is_empty();
                self.deregister_reader(pop_epoch);
                pop_is_empty
            } else {
                true
            };

            let is_empty = self.get_queue(push_epoch).is_empty() && pop_is_empty;
            self.deregister_reader(push_epoch);
            return is_empty;
        }
    }

    fn is_full(&self) -> bool {
        // the queue is full if push() fails
        loop {
            let push_epoch = self.push_epoch.load(Ordering::Acquire);
            if !self.register_reader(push_epoch) {
                continue;
            }
            let is_full = self.get_queue(push_epoch).is_full();
            self.deregister_reader(push_epoch);

            return is_full;
        }
    }
}

impl<T, Q, S> NewSized for GrowableQueueCore<T, Q, S>
where
    Q: NewSized,
{
    fn with_size(size: usize) -> GrowableQueueCore<T, Q, S> {
        GrowableQueueCore::with_slot(size)
    }
}

impl<S> NewSized for QueueCore<BoxedBuffer<S>>
where
    S: Default,
{
    fn with_size(size: usize) -> Self {
        Self::new_in(BoxedBuffer::new(size))
    }
}

/// A lock-free, non-blocking queue, that may dynamically grow its capacity.
pub struct DynamicQueue<T, S = Auto>
where
    S: SlotType<T>,
    T: AsPackedValue,
{
    inner: GrowableQueueCore<T, QueueCore<BoxedBuffer<S::Slot>>, S>,
}

impl<T> DynamicQueue<T, Auto>
where
    T: AsPackedValue,
{
    /// Constructs a new `DynamicQueue` with capacity `size` and slot type `Auto`.
    /// `T` must fit into the chosen slot type
    pub fn new(size: usize) -> Self {
        Self::with_slot::<Auto>(size)
    }

    /// Constructs a new `DynamicQueue` with capacity `size` and slot type `S`.
    /// `T` must fit into the slot type `S`
    pub fn with_slot<S>(size: usize) -> DynamicQueue<T, S>
    where
        S: SlotType<T>,
    {
        DynamicQueue {
            inner: GrowableQueueCore::with_slot::<S>(size),
        }
    }
}

impl<T, S> MPMCQueue for DynamicQueue<T, S>
where
    T: AsPackedValue,
    S: SlotType<T>,
{
    type Item = T;

    fn push(&self, item: Self::Item) -> Result<(), Self::Item> {
        self.inner.push(item)
    }

    fn pop(&self) -> Option<Self::Item> {
        self.inner.pop()
    }

    fn len(&self) -> usize {
        self.inner.len()
    }

    fn capacity(&self) -> usize {
        self.inner.capacity()
    }

    fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    fn is_full(&self) -> bool {
        self.inner.is_full()
    }
}

impl<T, S> Growable for DynamicQueue<T, S>
where
    T: AsPackedValue,
    S: SlotType<T>,
{
    fn grow_by(&self, by: usize) -> bool {
        self.inner.grow_by(by)
    }
}