Skip to content

Instantly share code, notes, and snippets.

@Jason5Lee
Last active July 9, 2020 06:11
Show Gist options
  • Save Jason5Lee/1d4f5c5d111d03cae72c04b2aeddd732 to your computer and use it in GitHub Desktop.
Save Jason5Lee/1d4f5c5d111d03cae72c04b2aeddd732 to your computer and use it in GitHub Desktop.
Non-blocking drop objects by a background thread, inspired by the "GC thread" concept in GC languages.
// [dependencies]
// lazy_static = "1.4"
// crossbeam-channel = "0.4"
use crossbeam_channel::{unbounded, SendError, Sender};
use lazy_static::lazy_static;
use std::thread;
use std::time::Duration;
lazy_static! {
pub static ref DROP: Sender<Box<dyn Send>> = {
let (sender, receiver) = unbounded();
thread::spawn(move || loop {
drop(receiver.recv())
});
sender
};
}
pub fn async_drop<T: Send + 'static>(t: T) -> Result<(), SendError<Box<dyn Send>>> {
DROP.send(Box::new(t))
}
struct SlowDrop(Duration, &'static str);
impl Drop for SlowDrop {
fn drop(&mut self) {
thread::sleep(self.0);
println!("{}", self.1)
}
}
fn run() {
let sd_abc = SlowDrop(Duration::from_secs(1), "abc");
let sd_123 = SlowDrop(Duration::from_secs(1), "123");
let sd_yes = SlowDrop(Duration::from_secs(1), "yes");
async_drop(23).unwrap();
async_drop(sd_abc).unwrap();
async_drop(sd_123).unwrap();
async_drop(sd_yes).unwrap();
}
fn main() {
run();
println!("Return from run");
std::thread::sleep(std::time::Duration::from_secs(4))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment