thebracket / ArdanUltimateRust-5Days

Accompanying the 5-class, 1 class per week series of Ultimate Rust: Foundations
100 stars 27 forks source link

ReadWriteLock does not work as its written #4

Closed suhasghorp closed 2 weeks ago

suhasghorp commented 3 weeks ago

ReadWriteLock compiles as its written but does not add new Strings to the lazy RwLocked vector. I had to modify the code as follows in case someone else faces the same issue. We need to explicity drop the "read" lock in every iteration.

` std::thread::spawn(|| { // background thread that keeps reading the USERS vec loop { let users = USERS.read().unwrap(); println!("List of users:{:?}", users); std::mem::drop(users); std::thread::sleep(std::time::Duration::from_secs(10)); } });

println!("Enter a user name or q to quit");
loop {        
    let entry = read_line();
    if entry == "q" {
        break;
    } else if let Ok(mut locked_vec) = USERS.try_write() {
        locked_vec.push(entry);
    } else {
        println!("could not get write lock");
    }
}`
thebracket commented 2 weeks ago

Good catch, thank you! I've updated the repo. The example was missing one line:

std::thread::spawn(|| {
        loop {
            println!("Current users (in a thread)");
            let users = USERS.read().unwrap();
            println!("{users:?}");
            std::mem::drop(users); // Release the lock before sleeping
            std::thread::sleep(std::time::Duration::from_secs(3));
        }
    });

Dropping the "read" lock before the sleep (rather than just letting it drop on the next loop iteration) prevents this bug from occurring. Otherwise the main loop will wait until the lock is available.