Skip to content

Instantly share code, notes, and snippets.

@junha1
Last active November 26, 2020 05:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save junha1/8ebaf53f46ea6fc14ab6797b9939b0f8 to your computer and use it in GitHub Desktop.
Save junha1/8ebaf53f46ea6fc14ab6797b9939b0f8 to your computer and use it in GitHub Desktop.
Join thread with a timeout
use std::thread;
use std::sync::mpsc::{Receiver, channel};
use std::time::Duration;
struct MyJoin<T> {
handle: thread::JoinHandle<T>,
signal: Receiver<()>
}
impl<T> MyJoin<T> {
fn join(self, timeout: Duration) -> Result<T, Self> {
if let Err(_) = self.signal.recv_timeout(timeout) {
return Err(self)
}
Ok(self.handle.join().unwrap())
}
}
fn my_spawn<T: Send + 'static, F: FnOnce() -> T + Send + 'static>(f: F) -> MyJoin<T> {
let (send, recv) = channel();
let t = thread::spawn(move || {
let x = f();
send.send(()).unwrap();
x
});
MyJoin {
handle: t,
signal: recv
}
}
fn main() {
let mut j = my_spawn(|| std::thread::sleep(Duration::from_secs(1)));
loop {
match j.join(Duration::from_millis(100)) {
Ok(_) => return,
Err(x) => {
println!("Failed to join within a timeout");
j = x
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment