I have this toy structure I'm playing around with:
pub struct Community {
pub community_contents: RwLock<CommunityContents>,
}
pub struct CommunityContents {
pub friends: RefCell<HashMap<FriendID, FriendData>>,
pub index: RefCell<HashMap<u64, BTreeMap<FriendID, FriendData>>>,
pub authenticated: bool,
pub age: u64,
pub height: u64,
}
My theory was to have an Arc around the RwLock of Community and then I could have multiple writers to the RwLock and these writers could independently/concurrently modify the friends and index fields of CommunityContents via Rc<RefCell.
Is this even possible? Will RwLock just not allow more than one writer at a time no matter what - in which case I should just remove the RefCells and simplify the whole structure?
No.
Arcdoes not allow mutation of the type it holds. Only immutable references can be shared, andArcis no different.From
Arcdocs:That means that you must store a type that has interior mutability...
RwLockis one of those types, and it behaves identically, no matter whether it's wrapped inArcor not.From
RwLockdocs:It's impossible to obtain mutable reference in two different places using safe Rust no matter what you do, the only way is using
unsafe {}, which results in undefined behaviour anyway, types likeRwLockdo useunsafe {}, but, they guarantee that the write (mutable access) is exclusive, in fact, it cannot be read if someone is writing to it, and it cannot be written to if someone is reading it, that's what that sentence means.