SPB Git

Repository Public

spsc.rs 4.5 KB 139 lines rust

1//! ORIX Sonata2//! File: crates/sonata-runtime/src/spsc.rs3//! Description: Bounded lock-free single-producer single-consumer queue (commands to the audio4//! thread, retired programs back from it). Wait-free push and pop, no allocation after creation.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use std::cell::UnsafeCell;10use std::mem::MaybeUninit;11use std::sync::atomic::{AtomicUsize, Ordering};12use std::sync::Arc;1314struct Ring<T> {15    slots: Box<[UnsafeCell<MaybeUninit<T>>]>,16    mask: usize,17    /// Next slot to read (owned by the consumer).18    head: AtomicUsize,19    /// Next slot to write (owned by the producer).20    tail: AtomicUsize,21}2223// SAFETY: a slot is accessed by the producer only between `tail` and `head + capacity`, and by the24// consumer only between `head` and `tail`; the atomics hand ownership of a slot from one to the other.25unsafe impl<T: Send> Send for Ring<T> {}26unsafe impl<T: Send> Sync for Ring<T> {}2728impl<T> Drop for Ring<T> {29    fn drop(&mut self) {30        let (mut h, t) = (*self.head.get_mut(), *self.tail.get_mut());31        while h != t {32            // SAFETY: slots in [head, tail) hold initialised values that nobody else can reach.33            unsafe { (*self.slots[h & self.mask].get()).assume_init_drop() };34            h = h.wrapping_add(1);35        }36    }37}3839pub struct Producer<T> {40    ring: Arc<Ring<T>>,41}4243pub struct Consumer<T> {44    ring: Arc<Ring<T>>,45}4647/// Creates a queue holding at least `capacity` items (rounded up to a power of two).48pub fn channel<T: Send>(capacity: usize) -> (Producer<T>, Consumer<T>) {49    let cap = capacity.max(2).next_power_of_two();50    let slots: Box<[UnsafeCell<MaybeUninit<T>>]> = (0..cap).map(|_| UnsafeCell::new(MaybeUninit::uninit())).collect();51    let ring = Arc::new(Ring { slots, mask: cap - 1, head: AtomicUsize::new(0), tail: AtomicUsize::new(0) });52    (Producer { ring: ring.clone() }, Consumer { ring })53}5455impl<T: Send> Producer<T> {56    /// Enqueues `value`; gives it back when the queue is full.57    pub fn push(&mut self, value: T) -> Result<(), T> {58        let r = &*self.ring;59        let tail = r.tail.load(Ordering::Relaxed);60        if tail.wrapping_sub(r.head.load(Ordering::Acquire)) > r.mask {61            return Err(value);62        }63        // SAFETY: the slot at `tail` is free (checked above) and only the producer writes it.64        unsafe { (*r.slots[tail & r.mask].get()).write(value) };65        r.tail.store(tail.wrapping_add(1), Ordering::Release);66        Ok(())67    }68    pub fn is_full(&self) -> bool {69        let r = &*self.ring;70        r.tail.load(Ordering::Relaxed).wrapping_sub(r.head.load(Ordering::Acquire)) > r.mask71    }72}7374impl<T: Send> Consumer<T> {75    pub fn pop(&mut self) -> Option<T> {76        let r = &*self.ring;77        let head = r.head.load(Ordering::Relaxed);78        if head == r.tail.load(Ordering::Acquire) {79            return None;80        }81        // SAFETY: the slot at `head` was initialised by the producer and published through `tail`.82        let v = unsafe { (*r.slots[head & r.mask].get()).assume_init_read() };83        r.head.store(head.wrapping_add(1), Ordering::Release);84        Some(v)85    }86    pub fn is_empty(&self) -> bool {87        let r = &*self.ring;88        r.head.load(Ordering::Relaxed) == r.tail.load(Ordering::Acquire)89    }90}9192#[cfg(test)]93mod tests {94    use super::*;9596    #[test]97    fn fifo_order_capacity_and_drop() {98        let (mut p, mut c) = channel::<Box<u32>>(4);99        for i in 0..4 {100            p.push(Box::new(i)).unwrap();101        }102        assert!(p.is_full());103        assert_eq!(*p.push(Box::new(9)).unwrap_err(), 9);104        assert_eq!(*c.pop().unwrap(), 0);105        p.push(Box::new(4)).unwrap();106        for i in 1..=4 {107            assert_eq!(*c.pop().unwrap(), i);108        }109        assert!(c.pop().is_none());110        p.push(Box::new(7)).unwrap(); // dropped with the ring111    }112113    #[test]114    fn two_threads_transfer_everything_in_order() {115        let (mut p, mut c) = channel::<u64>(64);116        let n = 200_000u64;117        let t = std::thread::spawn(move || {118            let mut i = 0;119            while i < n {120                if p.push(i).is_ok() {121                    i += 1;122                } else {123                    std::thread::yield_now();124                }125            }126        });127        let mut expect = 0;128        while expect < n {129            if let Some(v) = c.pop() {130                assert_eq!(v, expect);131                expect += 1;132            } else {133                std::thread::yield_now();134            }135        }136        t.join().unwrap();137    }138}139
Files main
Menu

Theme