| 1 |
/*! Waste Management |
| 2 |
|
| 3 |
Do you drive your own garbage to the landfill or compost heap? Maybe you should, |
| 4 |
but that’s a lot of work and takes time out of your day, so you probably don’t. |
| 5 |
Instead, you give it to a worker that specializes in managing objects at the end |
| 6 |
of their time in your service. |
| 7 |
|
| 8 |
This module moves objects from the threads where they were working to a single, |
| 9 |
global, worker thread when they go out of scope. Since an object that is going |
| 10 |
out of scope can no longer be used, you could say that it is *garbage*; since |
| 11 |
there is only one worker thread to receive all such objects, you could say that |
| 12 |
the worker *collects* them. Wink wink, nudge nudge. |
| 13 |
|
| 14 |
Users need only wrap their values in `BgDrop` to have their garbage collected. |
| 15 |
`BgDrop` only accepts `'static` values, since the values are being sent to |
| 16 |
another thread that makes no guarantees about timeliness of destruction, and |
| 17 |
thus the garbage cannot have any lingering ties to live objects in the rest of |
| 18 |
the program. |
| 19 |
|
| 20 |
When a `BgDrop` goes out of scope, it attempts to send its interior value to the |
| 21 |
collector thread. The first `BgDrop` to drop must start the collector thread, |
| 22 |
which may result in an indefinite block until the thread begins. Once the |
| 23 |
collector is running, all `BgDrop` drops will *attempt* to send their internal |
| 24 |
value to the collector for destruction. If the send fails, then the value will |
| 25 |
be dropped on the sending thread, rather than on the collector. |
| 26 |
|
| 27 |
You can prevent future collections with `cancel_collection()`, which destroys |
| 28 |
the channel used to move values to the collector thread. You can also get the |
| 29 |
thread key for the collector with `collector()`. If you need to ensure that all |
| 30 |
pending destructions occur before program exit, you should end your program with |
| 31 |
a `cancel_collection()` and then `collector().unwrap().join()`. The collector |
| 32 |
guarantees that objects queued for destruction are either enqueued for future |
| 33 |
destruction *or* destroyed immediately, so the collector thread *will* receive a |
| 34 |
signal for each object not destroyed on its prior thread. |
| 35 |
!*/ |
| 36 |
|
| 37 |
#![cfg(all(feature = "std", feature = "garbage"))] |
| 38 |
|
| 39 |
use once_cell::sync::OnceCell; |
| 40 |
|
| 41 |
use tap::Pipe; |
| 42 |
|
| 43 |
use std::{ |
| 44 |
collections::VecDeque, |
| 45 |
marker::PhantomData, |
| 46 |
mem::{ |
| 47 |
self, |
| 48 |
ManuallyDrop, |
| 49 |
}, |
| 50 |
ops::{ |
| 51 |
Deref, |
| 52 |
DerefMut, |
| 53 |
}, |
| 54 |
sync::{ |
| 55 |
mpsc, |
| 56 |
Mutex, |
| 57 |
MutexGuard, |
| 58 |
Once, |
| 59 |
RwLock, |
| 60 |
}, |
| 61 |
thread, |
| 62 |
}; |
| 63 |
|
| 64 |
use typemap::TypeMap; |
| 65 |
|
| 66 |
/** Run an object’s destructor in the background. |
| 67 |
|
| 68 |
When `BgDrop`-wrapped objects go out of scope, the `BgDrop` destructor attempts |
| 69 |
to use a global background-thread to receive the wrapped value, so that its |
| 70 |
destructor is run on the worker thread. If the thread running a `BgDrop` |
| 71 |
destructor is able to send the value to the worker, then it resumes immediately, |
| 72 |
and does not wait for the worker to get around to actually running the wrapped |
| 73 |
destructor. This is similar to the disposal semantics of many GC systems, though |
| 74 |
the actual system used to determine when an object becomes garbage is still the |
| 75 |
compiler’s static lifetime analyzer. |
| 76 |
|
| 77 |
All `BgDrop` types use the same persistent worker thread, minimizing the program |
| 78 |
cost of deferral. |
| 79 |
|
| 80 |
If the function [`wm::shutdown()`] is called, all future `BgDrop`s become a noöp |
| 81 |
and run their contained destructors on their local threads. |
| 82 |
|
| 83 |
[`wm::shutdown()`]: ../fn.shutdown.html |
| 84 |
**/ |
| 85 |
#[repr(transparent)] |
| 86 |
pub struct BgDrop<T: 'static> { |
| 87 |
inner: ManuallyDrop<T>, |
| 88 |
} |
| 89 |
|
| 90 |
impl<T: 'static> BgDrop<T> { |
| 91 |
/// Instructs an object to run its destructor in the background. |
| 92 |
/// |
| 93 |
/// This function modifies the wrapped object’s `Drop` implementation to try |
| 94 |
/// to, on `drop`, send the inner object to a background thread for actual |
| 95 |
/// destruction. If the object cannot be sent to the background when its |
| 96 |
/// wrapper goes out of scope, then its destructor runs immediately, in the |
| 97 |
/// thread that had been holding the object when the modified destructor was |
| 98 |
/// called. |
| 99 |
/// |
| 100 |
/// If the wrapped object is successfully sent to the background, the |
| 101 |
/// modified destructor exits, and the current thread resumes work. Once |
| 102 |
/// enqueued, the inner object is guaranteed to be *eventually* destroyed, |
| 103 |
/// unless the program exits in a manner that prevents the background |
| 104 |
/// collector from emptying its work queue. |
| 105 |
#[inline(always)] |
| 106 |
pub fn new(value: T) -> Self { |
| 107 |
Self { |
| 108 |
inner: ManuallyDrop::new(value), |
| 109 |
} |
| 110 |
} |
| 111 |
|
| 112 |
/// Removes the background-destruction marker, returning the interior value. |
| 113 |
#[inline(always)] |
| 114 |
pub fn into_inner(mut self) -> T { |
| 115 |
unsafe { ManuallyDrop::take(&mut self.inner) } |
| 116 |
} |
| 117 |
|
| 118 |
/// Attempt to prevent double-deferral, which would cause the outer to send |
| 119 |
/// the inner to the worker thread, making the worker thread send the |
| 120 |
/// *actual* inner to itself for destruction. This is safe, but stupid. |
| 121 |
#[inline(always)] |
| 122 |
#[doc(hidden)] |
| 123 |
pub fn bg_drop(self) -> Self { |
| 124 |
self |
| 125 |
} |
| 126 |
|
| 127 |
#[inline(always)] |
| 128 |
fn dtor(&mut self) { |
| 129 |
// No destructor, no problem! Quit. |
| 130 |
if !mem::needs_drop::<T>() { |
| 131 |
return; |
| 132 |
} |
| 133 |
|
| 134 |
// Ensure that the collector has been initialized. |
| 135 |
init(); |
| 136 |
|
| 137 |
// Pull the value into local scope, reärming the destructor. |
| 138 |
let val = unsafe { ManuallyDrop::take(&mut self.inner) }; |
| 139 |
|
| 140 |
// Get a local copy of the outbound channel, or exit. |
| 141 |
let sender = match sender() { |
| 142 |
Some(s) => s, |
| 143 |
None => return, |
| 144 |
}; |
| 145 |
|
| 146 |
// Enqueue the object into the transfer buffer. |
| 147 |
dq().entry::<Key<T>>() |
| 148 |
.or_insert_with(VecDeque::new) |
| 149 |
.pipe(|v| v.push_back(val)); |
| 150 |
|
| 151 |
// Send the dequeueïng destructor to the collector thread, or run it |
| 152 |
// locally if the send failed. |
| 153 |
if sender.send(dtor::<T>).is_err() { |
| 154 |
dtor::<T>(); |
| 155 |
} |
| 156 |
} |
| 157 |
} |
| 158 |
|
| 159 |
impl<T: 'static> AsRef<T> for BgDrop<T> { |
| 160 |
fn as_ref(&self) -> &T { |
| 161 |
&*self.inner |
| 162 |
} |
| 163 |
} |
| 164 |
|
| 165 |
impl<T: 'static> AsMut<T> for BgDrop<T> { |
| 166 |
fn as_mut(&mut self) -> &mut T { |
| 167 |
&mut *self.inner |
| 168 |
} |
| 169 |
} |
| 170 |
|
| 171 |
impl<T: 'static> Deref for BgDrop<T> { |
| 172 |
type Target = T; |
| 173 |
|
| 174 |
fn deref(&self) -> &Self::Target { |
| 175 |
&*self.inner |
| 176 |
} |
| 177 |
} |
| 178 |
|
| 179 |
impl<T: 'static> DerefMut for BgDrop<T> { |
| 180 |
fn deref_mut(&mut self) -> &mut Self::Target { |
| 181 |
&mut *self.inner |
| 182 |
} |
| 183 |
} |
| 184 |
|
| 185 |
impl<T: 'static> Drop for BgDrop<T> { |
| 186 |
fn drop(&mut self) { |
| 187 |
self.dtor(); |
| 188 |
} |
| 189 |
} |
| 190 |
|
| 191 |
/// Attaches a `BgDrop` constructor to all suitable types. |
| 192 |
pub trait BgDropExt: Sized + 'static { |
| 193 |
/// Modifies the object’s destructor to run in the background. |
| 194 |
/// |
| 195 |
/// When this value goes out of scope, it will attempt to send itself to a |
| 196 |
/// background thread where its *actual* destructor will be run. The actual |
| 197 |
/// destructor will run on the local thread only if the transfer to the |
| 198 |
/// background worker was unable to occur. |
| 199 |
/// |
| 200 |
/// The background worker is started only when the first value marked for |
| 201 |
/// deferred destruction actually drops, so the first call will block until |
| 202 |
/// the disposal system is initialized. |
| 203 |
/// |
| 204 |
/// The first value of each *type* to be deferred will modify the disposal |
| 205 |
/// system to handle its type. |
| 206 |
/// |
| 207 |
/// All subsequent drops of a type that has been deferred before will happen |
| 208 |
/// nearly instantaneously, as they must only observe that the system is set |
| 209 |
/// up for them, and move the value into the transfer queue. |
| 210 |
/// |
| 211 |
/// # Usage |
| 212 |
/// |
| 213 |
/// ```rust |
| 214 |
/// use wyz::wm::BgDropExt; |
| 215 |
/// |
| 216 |
/// vec![1, 2, 3, 4, 5].bg_drop(); |
| 217 |
/// vec![6, 7, 8, 9, 10].bg_drop(); |
| 218 |
/// ``` |
| 219 |
/// |
| 220 |
/// If you need to guarantee that your program remains open until all |
| 221 |
/// deferred objects are destroyed, you can block on [`wm::shutdown()`]. |
| 222 |
/// |
| 223 |
/// [`wm::shutdown()`]: ../fn.shutdown.html |
| 224 |
fn bg_drop(self) -> BgDrop<Self> { |
| 225 |
BgDrop::new(self) |
| 226 |
} |
| 227 |
} |
| 228 |
|
| 229 |
impl<T: Sized + 'static> BgDropExt for T { |
| 230 |
} |
| 231 |
|
| 232 |
/** Stop the background disposal system. |
| 233 |
|
| 234 |
This function shuts down the disposal system, and ensures that all deferred |
| 235 |
destructors in the program are correctly handled. It disables all *future* |
| 236 |
deferred-drops from sending values to the worker thread, which forces them to |
| 237 |
run their destructors locally. In the meantime, the worker thread will pull all |
| 238 |
remaining values out of its work queue and destroy them, then terminate once it |
| 239 |
sees that its queue has been closed. |
| 240 |
|
| 241 |
When this function returns, the worker thread will have emptied its queue, torn |
| 242 |
down its transfer system, and exited. |
| 243 |
|
| 244 |
You may call this function more than once; it is idempotent. The worker system |
| 245 |
is program-global, and will only be started once and stopped once. Once this |
| 246 |
function is called, the program will never run deferred disposal again. |
| 247 |
|
| 248 |
Rust does not provide a portable `atexit` behavior, so you are responsible for |
| 249 |
calling this before your program terminates if you want to ensure that all |
| 250 |
deferred destructions actually take place. Future versions of this library may |
| 251 |
register `wm::shutdown()` with the sytem `atexit` handler. If this occurs, the |
| 252 |
function will be marked as deprecated on platforms where it is set. |
| 253 |
**/ |
| 254 |
pub fn shutdown() { |
| 255 |
static STOP: Once = Once::new(); |
| 256 |
STOP.call_once(|| { |
| 257 |
// Destroy the sender handle. |
| 258 |
let _: Option<AssertThreadsafe<mpsc::Sender<Dtor>>> = SEND |
| 259 |
.get() |
| 260 |
// Lock the write guard, |
| 261 |
.and_then(|rw| rw.write().ok()) |
| 262 |
// And remove the sender handle from it. |
| 263 |
.and_then(|mut sender| sender.take()); |
| 264 |
// Close the destructor thread. |
| 265 |
let _: Option<()> = JOIN |
| 266 |
.get() |
| 267 |
// Lock the thread’s mutex, |
| 268 |
.and_then(|mx| mx.lock().ok()) |
| 269 |
// Remove the handle from it, |
| 270 |
.and_then(|mut mg| mg.take()) |
| 271 |
// And await the thread’s termination. |
| 272 |
.and_then(|jh| jh.join().ok()); |
| 273 |
}); |
| 274 |
} |
| 275 |
|
| 276 |
// Disposal system implementation |
| 277 |
|
| 278 |
type Dtor = fn() -> (); |
| 279 |
|
| 280 |
// The sender is never used concurrently. |
| 281 |
static SEND: OnceCell<RwLock<Option<AssertThreadsafe<mpsc::Sender<Dtor>>>>> = |
| 282 |
OnceCell::new(); |
| 283 |
// The map is only ever used behind a mutex lock. |
| 284 |
static DUMP: OnceCell<Mutex<AssertThreadsafe<TypeMap>>> = OnceCell::new(); |
| 285 |
static JOIN: OnceCell<Mutex<Option<thread::JoinHandle<()>>>> = OnceCell::new(); |
| 286 |
|
| 287 |
/// Initialize the collection system. |
| 288 |
#[inline(never)] |
| 289 |
fn init() { |
| 290 |
let (send, recv) = mpsc::channel::<Dtor>(); |
| 291 |
|
| 292 |
// Establish a base sending channel. This holds the collector open until |
| 293 |
// `cancel()` is called. |
| 294 |
SEND.get_or_init(|| { |
| 295 |
send.pipe(AssertThreadsafe::new) |
| 296 |
.pipe(Some) |
| 297 |
.pipe(RwLock::new) |
| 298 |
}); |
| 299 |
|
| 300 |
// Establish a transfer queue for all types. |
| 301 |
DUMP.get_or_init(|| { |
| 302 |
TypeMap::new().pipe(AssertThreadsafe::new).pipe(Mutex::new) |
| 303 |
}); |
| 304 |
|
| 305 |
// Start the collector thread. |
| 306 |
JOIN.get_or_init(|| { |
| 307 |
thread::spawn(move || { |
| 308 |
while let Ok(ev) = recv.recv() { |
| 309 |
(ev)() |
| 310 |
} |
| 311 |
let _ = mem::replace(&mut **dq(), TypeMap::new()); |
| 312 |
}) |
| 313 |
.pipe(Some) |
| 314 |
.pipe(Mutex::new) |
| 315 |
}); |
| 316 |
|
| 317 |
// TODO(myrrlyn): Register an `atexit` handler to run `shutdown()`. |
| 318 |
} |
| 319 |
|
| 320 |
/// Lock the transfer map. |
| 321 |
fn dq() -> MutexGuard<'static, AssertThreadsafe<TypeMap>> { |
| 322 |
unsafe { DUMP.get_unchecked() } |
| 323 |
.lock() |
| 324 |
.expect("Collection buffer should never observe a panic") |
| 325 |
} |
| 326 |
|
| 327 |
/// Pull the front object out of a typed queue, and destroy it. |
| 328 |
fn dtor<T: 'static>() { |
| 329 |
// Binding a value causes it to drop *after* any temporaries created in its |
| 330 |
// construction. |
| 331 |
let _tmp = dq() |
| 332 |
// View the deque containing objects of this type. |
| 333 |
.get_mut::<Key<T>>() |
| 334 |
// And pop the front value in the queue. It is acceptable to fail. |
| 335 |
.and_then(VecDeque::pop_front); |
| 336 |
// The mutex lock returned by `dq()` drops immediately after the semicolon, |
| 337 |
// and the `_tmp` binding drops immediately before the terminating brace. |
| 338 |
} |
| 339 |
|
| 340 |
/// Get a local copy of the sender, free of threading concerns. |
| 341 |
fn sender() -> Option<mpsc::Sender<Dtor>> { |
| 342 |
// `sender` is only called after `SEND` is initialized |
| 343 |
unsafe { SEND.get_unchecked() } |
| 344 |
// Quit if the send channel could not be opened for reading |
| 345 |
.read() |
| 346 |
.ok()? |
| 347 |
// or if it contains `None` |
| 348 |
.as_ref()? |
| 349 |
.inner |
| 350 |
// and copy the sender into the local thread. |
| 351 |
.clone() |
| 352 |
.pipe(Some) |
| 353 |
} |
| 354 |
|
| 355 |
/// Look up a type’s location in the transfer map. |
| 356 |
struct Key<T: 'static>(PhantomData<T>); |
| 357 |
|
| 358 |
impl<T: 'static> typemap::Key for Key<T> { |
| 359 |
/// The transfer map holds some form of collection of the transferred types. |
| 360 |
/// |
| 361 |
/// The specific collection type is irrelevant, as long as it supports both |
| 362 |
/// insertion and removal, and has reasonable behavior characteristics. |
| 363 |
/// Since the map has to be completely locked for any transfer event, as the |
| 364 |
/// first transfer of each type must insert its queue into the map, there is |
| 365 |
/// no advantage in trying to make this mpsc-friendly. |
| 366 |
/// |
| 367 |
/// If Rust were to allow a construction like |
| 368 |
/// |
| 369 |
/// ```rust,ignore |
| 370 |
/// fn type_chan<T: 'static>() -> ( |
| 371 |
/// &'static mpsc::Sender<T>, |
| 372 |
/// &'static mpsc::Receiver<T>, |
| 373 |
/// ) { |
| 374 |
/// static MAKE: Once = Once::new(); |
| 375 |
/// static mut CHAN: Option<(mpsc::Sender<T>, mpsc::Receiver<T>) = None; |
| 376 |
/// MAKE.call_once(|| unsafe { |
| 377 |
/// CHAN = Some(mpsc::channel()); |
| 378 |
/// }); |
| 379 |
/// (&CHAN.0, &CHAN.1) |
| 380 |
/// } |
| 381 |
/// ``` |
| 382 |
/// |
| 383 |
/// then a dynamic type-map would not be necessary at all, since each type |
| 384 |
/// would be granted its own dedicated channel at compile-time. But Rust |
| 385 |
/// does not, so, it is. |
| 386 |
type Value = VecDeque<T>; |
| 387 |
} |
| 388 |
|
| 389 |
/** Get off my back, `rustc`. |
| 390 |
|
| 391 |
This is required because `static` vars must be `Sync`, and the thread-safety |
| 392 |
wrappers in use apparently inherit the `Sync`hronicity of their wrapped types. |
| 393 |
This module uses them correctly, and does not permit escape, so this struct is |
| 394 |
needed to get the compiler to accept our use. |
| 395 |
**/ |
| 396 |
#[repr(transparent)] |
| 397 |
struct AssertThreadsafe<T> { |
| 398 |
inner: T, |
| 399 |
} |
| 400 |
|
| 401 |
impl<T> AssertThreadsafe<T> { |
| 402 |
fn new(inner: T) -> Self { |
| 403 |
Self { inner } |
| 404 |
} |
| 405 |
} |
| 406 |
|
| 407 |
unsafe impl<T> Send for AssertThreadsafe<T> { |
| 408 |
} |
| 409 |
|
| 410 |
unsafe impl<T> Sync for AssertThreadsafe<T> { |
| 411 |
} |
| 412 |
|
| 413 |
impl<T> Deref for AssertThreadsafe<T> { |
| 414 |
type Target = T; |
| 415 |
|
| 416 |
fn deref(&self) -> &Self::Target { |
| 417 |
&self.inner |
| 418 |
} |
| 419 |
} |
| 420 |
|
| 421 |
impl<T> DerefMut for AssertThreadsafe<T> { |
| 422 |
fn deref_mut(&mut self) -> &mut Self::Target { |
| 423 |
&mut self.inner |
| 424 |
} |
| 425 |
} |
| 426 |
|
| 427 |
#[cfg(test)] |
| 428 |
mod tests { |
| 429 |
use super::*; |
| 430 |
use std::{ |
| 431 |
sync::atomic::{ |
| 432 |
AtomicUsize, |
| 433 |
Ordering::Relaxed, |
| 434 |
}, |
| 435 |
thread, |
| 436 |
time::Duration, |
| 437 |
}; |
| 438 |
|
| 439 |
#[test] |
| 440 |
fn trash_pickup() { |
| 441 |
static COUNTER: AtomicUsize = AtomicUsize::new(0); |
| 442 |
|
| 443 |
struct Deferrer<F: FnMut()>(F); |
| 444 |
|
| 445 |
impl<F: FnMut()> Drop for Deferrer<F> { |
| 446 |
fn drop(&mut self) { |
| 447 |
(self.0)() |
| 448 |
} |
| 449 |
} |
| 450 |
|
| 451 |
let kept = Deferrer(|| { |
| 452 |
COUNTER.fetch_add(1, Relaxed); |
| 453 |
}); |
| 454 |
let sent = Deferrer(|| { |
| 455 |
COUNTER.fetch_add(1, Relaxed); |
| 456 |
}) |
| 457 |
.bg_drop(); |
| 458 |
|
| 459 |
drop(kept); |
| 460 |
drop(sent); |
| 461 |
|
| 462 |
while COUNTER.load(Relaxed) < 2 { |
| 463 |
thread::sleep(Duration::from_millis(100)); |
| 464 |
} |
| 465 |
} |
| 466 |
} |