#Sharing a deadline between threads. What's the best way to do this?
1 messages · Page 1 of 1 (latest)
use std::time::Instant;
use std::sync::{Arc};
use std::sync::Mutex;
use std::time::Duration;
fn main() {
// makke an arc mutex of deadline
let deadline = Arc::new(Mutex::new(Instant::now() + Duration::from_secs(1)));
// spawn some threads that exit when the deadline ends
for i in 0..1
{
let deadline_clone = Arc::clone(&deadline);
std::thread::spawn(move || {
println!("Thread {} spawned", i);
loop {
// sleep for a second
std::thread::sleep(std::time::Duration::from_secs(1));
println!("Thread {} sleeping, deadline is {:?}", i, *deadline_clone.lock().unwrap());
if Instant::now() > *deadline_clone.lock().unwrap() {
println!("Thread {} exiting...", i);
return;
}
}
});
}
// keep extending the deadline
for _ in 0..10
{
// add one second to the deadline
*deadline.lock().unwrap() += Duration::from_secs(1);
println!("Deadline extended to {:?}", deadline);
std::thread::sleep(std::time::Duration::from_secs(1));
}
}
Usually for that you'd use RwLock instead of Mutex. Also, if you spawn them in a scoped thread, you don't need the Arc.