Files
Lyrebird/Sources/Lyrebird/Engine/SPSCQueue.swift
T
2026-06-01 18:27:40 -07:00

67 lines
2.8 KiB
Swift

// SPSCQueue.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Synchronization
/// Single-Producer Single-Consumer lock-free ring buffer.
/// Capacity must be an exact power of two (e.g. 256, 512, 1024).
/// No allocation after init; safe to use on the RT audio thread (consumer side).
public final class SPSCQueue<T>: @unchecked Sendable {
private var buffer: [T?]
private let mask: Int
// Unbounded monotonic counters; actual index = value & mask
private let writeIdx: Atomic<Int> = Atomic<Int>(0)
private let readIdx: Atomic<Int> = Atomic<Int>(0)
/// The actual number of slots in the queue. Always a power of two.
public var capacity: Int { mask + 1 }
public init(capacity: Int) {
precondition(
capacity > 0 && capacity & (capacity - 1) == 0,
"SPSCQueue capacity \(capacity) must be a power of two (e.g. 256, 512, 1024)."
)
self.mask = capacity - 1
self.buffer = [T?](repeating: nil, count: capacity)
}
/// Enqueue a value. Called from the producer thread only.
/// Returns false if the queue is full.
@discardableResult
public func enqueue(_ value: T) -> Bool {
let write: Int = writeIdx.load(ordering: .relaxed)
let read: Int = readIdx.load(ordering: .acquiring)
let capacity: Int = mask + 1
guard write - read < capacity else { return false }
buffer[write & mask] = value
writeIdx.store(write + 1, ordering: .releasing)
return true
}
/// Dequeue a value. Called from the consumer thread only.
/// Returns nil if the queue is empty.
///
/// The slot is cleared to `nil` after the value is read so the queue does not retain
/// any strong references beyond what the consumer holds. Without this, a class-typed
/// `T` (or an enum case carrying class payloads — e.g. `ScheduledEvent` holding
/// `Synthesizer` / `PreparedNode`) would keep its previous occupant alive in the ring
/// slot until the next `enqueue` happens to wrap to the same index, which under sparse
/// traffic with `eventQueueCapacity = 1024` could be thousands of blocks. The extra
/// ARC release on the consumer thread is intentional and accepted: when the consumer
/// is the RT audio thread, the class payload would be released anyway via the returned
/// `value` going out of scope shortly after dequeue.
public func dequeue() -> T? {
let read: Int = readIdx.load(ordering: .relaxed)
let write: Int = writeIdx.load(ordering: .acquiring)
guard read < write else { return nil }
let value: T? = buffer[read & mask]
buffer[read & mask] = nil
readIdx.store(read + 1, ordering: .releasing)
return value
}
}