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
// Augmented Audio: Audio libraries and applications
// Copyright (c) 2022 Pedro Tacla Yamada
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//! Batteries included solution to using reference counted values on the audio-thread.
//!
//! Wraps `basedrop` so that smart pointers are dropped on a background thread. Exposes a default
//! global GC thread and helpers to create pointers attached to it.
//!
//! # Collection frequency
//! Collection is based on polling the queue every 100ms by default.
//!
//! If references are created and dropped very frequently this strategy is not adequate. This also
//! adds some small overhead.
use std::sync::{Arc, Mutex};
#[cfg(not(target_arch = "wasm32"))]
use std::thread;
use std::time::Duration;
use basedrop::Collector;
pub use basedrop::{Handle, Owned, Shared, SharedCell};
use lazy_static::lazy_static;
use thiserror::Error;
#[cfg(target_arch = "wasm32")]
use wasm_thread as thread;
lazy_static! {
static ref GARBAGE_COLLECTOR: GarbageCollector = GarbageCollector::default();
}
/// Return a reference to a global GC instance
pub fn current() -> &'static GarbageCollector {
&GARBAGE_COLLECTOR
}
/// Return a handle to a global GC instance
pub fn handle() -> &'static Handle {
GARBAGE_COLLECTOR.handle()
}
/// Create a new [`basedrop::SharedCell`] value using the default global [`GarbageCollector`]
/// instance.
pub fn make_shared_cell<T: Send + 'static>(value: T) -> SharedCell<T> {
SharedCell::new(make_shared(value))
}
/// Create a new [`basedrop::Shared`] value using the default global [`GarbageCollector`]
/// instance.
pub fn make_shared<T: Send + 'static>(value: T) -> Shared<T> {
Shared::new(handle(), value)
}
/// Errors that may be emitted when stopping the GC
#[derive(Debug, Error)]
pub enum GarbageCollectorError {
/// Emitted if the GC thread panicked during a GC run
#[error("Failed to acquire lock")]
LockError,
/// Emitted if the GC thread panicked at another point
#[error("Failed to join the GC thread")]
JoinError,
}
struct GarbageCollectorState {
running: bool,
collect_interval: Duration,
}
/// Wraps [`basedrop::Collector`] with a polling GC thread.
///
/// This drops reference counted variables on a dedicated thread to avoid deallocating from the
/// audio thread.
pub struct GarbageCollector {
collector: Arc<Mutex<Collector>>,
state: Arc<Mutex<GarbageCollectorState>>,
thread: Option<thread::JoinHandle<()>>,
handle: Handle,
}
impl Default for GarbageCollector {
fn default() -> Self {
Self::new(Duration::from_millis(100))
}
}
impl GarbageCollector {
/// Create the collector and start the garbage collector thread
pub fn new(collect_interval: Duration) -> Self {
let collector = Collector::new();
let handle = collector.handle();
let collector = Arc::new(Mutex::new(collector));
let state = Arc::new(Mutex::new(GarbageCollectorState {
running: true,
collect_interval,
}));
let thread = {
let collector = collector.clone();
let state = state.clone();
thread::Builder::new()
.name(String::from("gc-thread"))
.spawn(move || run_collector_loop(collector, state))
.expect("Failed to start GC thread")
};
GarbageCollector {
collector,
thread: Some(thread),
handle,
state,
}
}
/// Stop & join the collector thread.
pub fn stop(&mut self) -> Result<(), GarbageCollectorError> {
self.state
.lock()
.map(|mut state| {
state.running = false;
})
.map_err(|_| GarbageCollectorError::LockError)?;
if let Some(thread) = self.thread.take() {
thread
.join()
.map_err(|_| GarbageCollectorError::JoinError)?;
}
Ok(())
}
/// Get a handle to the collector. Does not lock.
pub fn handle(&self) -> &Handle {
&self.handle
}
/// Force GC on the current thread & return whether it was successful.
/// Tries to acquire a lock on the collector.
#[allow(dead_code)]
pub fn blocking_collect(&self) -> bool {
self.collector
.lock()
.map(|mut collector| {
collector.collect();
true
})
.unwrap_or(false)
}
/// Gets the number of live allocations associated with the `Collector`.
/// Tries to acquire a lock on the collector.
#[allow(dead_code)]
pub fn blocking_alloc_count(&self) -> usize {
self.collector
.lock()
.map(|collector| collector.alloc_count())
.unwrap_or(0)
}
}
fn run_collector_loop(collector: Arc<Mutex<Collector>>, state: Arc<Mutex<GarbageCollectorState>>) {
log::info!("Garbage collector thread started");
loop {
let (collect_interval, is_running) = state
.lock()
.map(|state| (state.collect_interval, state.running))
.unwrap_or((Duration::default(), false));
if !is_running {
log::info!("Garbage collector thread stopping");
return;
}
let collector = collector.lock().map(|mut collector| {
collector.collect();
});
if collector.is_err() {
log::warn!("Garbage collector thread failing due to lock error");
return;
}
std::thread::sleep(collect_interval);
}
}
#[cfg(test)]
mod test {
use basedrop::*;
use super::*;
#[test]
fn test_get_global_gc() {
let gc = current();
assert!(gc.blocking_collect());
let _ = gc.blocking_alloc_count();
}
#[test]
fn test_make_shared() {
let _ = make_shared(10);
}
#[test]
fn test_make_shared_cell() {
let c = make_shared_cell(10);
c.set(make_shared(22));
assert_eq!(*c.get(), 22);
drop(c);
let _ = current().blocking_alloc_count();
current().blocking_collect();
}
#[test]
fn test_default_garbage_collector() {
let mut gc = GarbageCollector::default();
gc.stop().unwrap();
}
#[test]
fn test_create_stop_collector() {
wisual_logger::init_from_env();
let mut gc = GarbageCollector::new(Duration::from_secs(1));
gc.stop().unwrap();
}
#[test]
fn test_gc_will_run_after_period() {
wisual_logger::init_from_env();
let mut gc = GarbageCollector::new(Duration::from_millis(10));
assert_eq!(gc.blocking_alloc_count(), 0);
{
let _s1 = Shared::new(gc.handle(), 10);
let _s2 = Shared::new(gc.handle(), 10);
assert_eq!(gc.blocking_alloc_count(), 2);
}
std::thread::sleep(Duration::from_millis(50));
assert_eq!(gc.blocking_alloc_count(), 0);
gc.stop().unwrap();
}
#[test]
fn test_gc_will_run_with_blocking_collect() {
wisual_logger::init_from_env();
let mut gc = GarbageCollector::new(Duration::from_millis(100));
assert_eq!(gc.blocking_alloc_count(), 0);
{
let _s1 = Shared::new(gc.handle(), 10);
let _s2 = Shared::new(gc.handle(), 10);
assert_eq!(gc.blocking_alloc_count(), 2);
}
assert_eq!(gc.blocking_collect(), true);
assert_eq!(gc.blocking_alloc_count(), 0);
gc.stop().unwrap();
}
}