-
-
Save salewski/f5ab6003ff81b6cbed2cfaa1e8261b16 to your computer and use it in GitHub Desktop.
Join thread with a timeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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