RwLock in Rust
Many readers or one writer: the right lock when reads dominate.
use std::sync::{Arc, RwLock};
use std::thread;
fn main() {
let table = Arc::new(RwLock::new(vec!["basics".to_string()]));
let writer = {
let table = Arc::clone(&table);
thread::spawn(move || {
table.write().unwrap().push("errors".to_string());
})
};
writer.join().unwrap();
let readers: Vec<_> = (0..3)
.map(|id| {
let table = Arc::clone(&table);
thread::spawn(move || {
let tours = table.read().unwrap();
println!("{id} sees {} tours", tours.len());
})
})
.collect();
for r in readers {
r.join().unwrap();
}
}
How it works
readmay be held by several threads at once.writewaits for every reader to finish.- Both return guards that release on drop.
Keywords and builtins used here
Vecfnforinletmainmoveuse
The run, in numbers
- Lines
- 28
- Characters to type
- 514
- Tokens
- 195
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 111 seconds.
Step 2 of 3 in Shared state, step 5 of 15 in Concurrency & async.