b6fdee8bfc
Consolidated release: the cross-platform Linux port (engine, generators, CLI, REPL, NRT, portable DSP), live ALSA audio + ALSA MIDI + POSIX OSC + portable WAV codec, the GTK4 GUI (LyrebirdUI on the SwiftOpenUI backend), and the Linux live-coding scratchpad (LiveCompile). Apple platforms unchanged; all additive. See RELEASES.md and LINUX_README.md. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
161 lines
6.1 KiB
Swift
161 lines
6.1 KiB
Swift
// RTThreadIdentity.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
// Thread-local-storage APIs: pthread (`pthread_key_*` / `*specific`) on Apple &
|
|
// POSIX, Win32 (`Tls*`) on Windows.
|
|
#if canImport(Darwin)
|
|
import Darwin
|
|
#elseif canImport(WinSDK)
|
|
import WinSDK
|
|
#elseif canImport(Glibc)
|
|
import Glibc
|
|
#elseif canImport(Musl)
|
|
import Musl
|
|
#endif
|
|
|
|
/// Identifies whether the calling thread is currently inside an audio driver's
|
|
/// render callback.
|
|
///
|
|
/// Used by DEBUG-only asserts in non-RT-safe APIs (e.g. ``ValueComputable``)
|
|
/// to trap when those APIs are mistakenly called from the RT thread.
|
|
///
|
|
/// Mechanism: each RT driver's `render(...)` entry point calls
|
|
/// ``markCurrentThreadAsRT()`` on first invocation. The marker is stored in
|
|
/// pthread thread-local storage via `pthread_setspecific` — an O(1) pointer
|
|
/// write that is allocation-free and signal-safe.
|
|
///
|
|
/// In release builds the marker is still set (one pointer write per render
|
|
/// callback entry — negligible cost) but is never read, so the work is
|
|
/// effectively dead-stripped if linkers elect to remove the assert call
|
|
/// sites. Set-once-per-thread optimisation (skipping the `setspecific` when
|
|
/// the slot is already marked) is intentional to keep the per-callback cost
|
|
/// at one TLS pointer read in the steady state.
|
|
internal enum RTThreadIdentity {
|
|
|
|
// MARK: - TLS key
|
|
|
|
/// Sentinel bit pattern stored in the TLS slot to mark "this is an RT
|
|
/// thread". Bridged to the pointer type the TLS APIs expect at use sites.
|
|
/// Any non-zero bit pattern works; `1` is distinct from any real heap
|
|
/// address.
|
|
private static let _markerBitPattern: UInt = 1
|
|
|
|
/// TLS key/index. Created lazily on first access — always from a non-RT
|
|
/// call site (engine init / driver setup) because ``warmUp()`` is invoked
|
|
/// there, so the allocating call (`pthread_key_create` / `TlsAlloc`) never
|
|
/// runs on the RT thread. Written exactly once (Swift's static-let
|
|
/// guarantee), read-only thereafter.
|
|
#if canImport(WinSDK)
|
|
private static let _tlsIndex: DWORD = {
|
|
let index: DWORD = TlsAlloc()
|
|
// TLS_OUT_OF_INDEXES == 0xFFFFFFFF == DWORD.max.
|
|
precondition(index != DWORD.max, "TlsAlloc failed")
|
|
return index
|
|
}()
|
|
#else
|
|
private static let _key: pthread_key_t = {
|
|
var key: pthread_key_t = 0
|
|
let status: Int32 = pthread_key_create(&key, nil)
|
|
precondition(status == 0, "pthread_key_create failed with status \(status)")
|
|
return key
|
|
}()
|
|
#endif
|
|
|
|
/// Read the calling thread's TLS slot. O(1), allocation-free, RT-safe.
|
|
@inline(__always)
|
|
private static func _tlsGet() -> UnsafeMutableRawPointer? {
|
|
#if canImport(WinSDK)
|
|
return TlsGetValue(_tlsIndex)
|
|
#else
|
|
return pthread_getspecific(_key)
|
|
#endif
|
|
}
|
|
|
|
/// Write the calling thread's TLS slot. O(1), allocation-free, RT-safe.
|
|
@inline(__always)
|
|
private static func _tlsSet(_ value: UnsafeMutableRawPointer?) {
|
|
#if canImport(WinSDK)
|
|
_ = TlsSetValue(_tlsIndex, value)
|
|
#else
|
|
pthread_setspecific(_key, value)
|
|
#endif
|
|
}
|
|
|
|
// MARK: - API
|
|
|
|
/// Force lazy initialisation of the TLS key from a known non-RT call
|
|
/// site (engine init / driver setup). Avoids a first-touch allocation on
|
|
/// the RT thread.
|
|
internal static func warmUp() {
|
|
#if canImport(WinSDK)
|
|
_ = _tlsIndex
|
|
#else
|
|
_ = _key
|
|
#endif
|
|
}
|
|
|
|
/// Mark the calling thread as an RT render thread. Idempotent — safe to
|
|
/// call on every render callback entry; only writes the TLS slot when it
|
|
/// isn't already marked.
|
|
///
|
|
/// RT-safe: at most one TLS write per thread, otherwise a single TLS
|
|
/// pointer comparison. No allocation, no locking.
|
|
internal static func markCurrentThreadAsRT() {
|
|
let sentinel: UnsafeMutableRawPointer? = UnsafeMutableRawPointer(bitPattern: _markerBitPattern)
|
|
if _tlsGet() != sentinel {
|
|
_tlsSet(sentinel)
|
|
}
|
|
}
|
|
|
|
/// `true` if the calling thread has been marked as an RT render thread.
|
|
///
|
|
/// Read-only fast path: single TLS pointer comparison. Safe to call from
|
|
/// any thread.
|
|
internal static var isCurrentThreadRT: Bool {
|
|
let sentinel: UnsafeMutableRawPointer? = UnsafeMutableRawPointer(bitPattern: _markerBitPattern)
|
|
return _tlsGet() == sentinel
|
|
}
|
|
|
|
#if DEBUG
|
|
/// TEST-ONLY: clear the RT marker on the calling thread.
|
|
///
|
|
/// Production never unmarks — an RT render thread stays an RT render thread for the
|
|
/// engine's life. But tests that call ``markCurrentThreadAsRT()`` on a transient
|
|
/// `DispatchQueue(label:)` worker must clear it before that thread returns to the
|
|
/// system pool; otherwise the stale marker can false-trip `_lyrebirdAssertNotOnRTThread`
|
|
/// in a later test that the pool hands the same thread. Not compiled in release.
|
|
internal static func _clearCurrentThreadRTMarkForTesting() {
|
|
_tlsSet(nil)
|
|
}
|
|
#endif
|
|
}
|
|
|
|
// MARK: - DEBUG assert helper
|
|
|
|
#if DEBUG
|
|
/// Trap when invoked from the RT render thread. Used by non-RT-safe APIs
|
|
/// (``ValueComputable`` conformers, language-side helpers) to catch misuse
|
|
/// at first call during development.
|
|
///
|
|
/// Release builds compile this away entirely — no code, no symbol.
|
|
///
|
|
/// The DEBUG branch keeps the abort message a `StaticString` literal so the
|
|
/// trap path does not heap-allocate before terminating. The call-site
|
|
/// function name is preserved through the `preconditionFailure` file/line
|
|
/// parameters (`#file` / `#line` default arguments captured automatically),
|
|
/// which the Swift runtime prints alongside the message — that's where the
|
|
/// caller identity surfaces in the crash log. Constructing
|
|
/// `"\(caller) called on RT thread..."` would allocate a `String` on the
|
|
/// RT thread, which is itself a CLAUDE.md hard violation.
|
|
internal func _lyrebirdAssertNotOnRTThread() {
|
|
if RTThreadIdentity.isCurrentThreadRT {
|
|
preconditionFailure("Non-RT API called on RT audio render thread. See ValueComputable.md for guidance.")
|
|
}
|
|
}
|
|
#else
|
|
internal func _lyrebirdAssertNotOnRTThread() {}
|
|
#endif
|