I have a bucket of objects that need to accumulate values. It's protected by an RwLock
, and as such I also keep around its write lock. I want to keep a single write lock for the duration of the process.
For example:
use std::sync::RwLock;
fn main() {
let locked = RwLock::new(Vec::<u32>::new());
// this is the entry point for real-world code
let mut writer = locked.write().unwrap();
// copy into 'locked' until it is full (has 4 items)
for v in 0..100 {
if writer.len() > 4 {
// discard 'writer' and 'locked', create anew
locked = RwLock::new(Vec::<u32>::new());
writer = locked.write().unwrap();
}
writer.push(v);
}
}
While my example operates on fixed data, and so appears to not need the RwLock
at all, the real code would enter at "real code" and not necessarily exit on the boundary of locked
becoming "full".
How do I create a new locked
and writer
object when needed without the borrow-checker disagreeing?