#Sharing a deadline between threads. What's the best way to do this?

1 messages · Page 1 of 1 (latest)

red dock
#

Currently I have this code, I think it's a bit over-the-top. With a Mutex in an Arc. Is there a better way to do this? My threads only ever READ from the deadline, and the main thread writes to it

#
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));
    }
}
wild coral
#

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.