Closed suhasghorp closed 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.
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)); } });