Hi "Rusters"
I have a multithread application where one of threads adding and deleting elements from HashMap and other few threads only reading from that map, so by logic it is guaranteed that other maps don't have a writable access to that map.
I can implement this with Arc<Mutex<HashMap<String, SomeData>>>, but in this case if some of the threads starting reading process, others would be waiting until Mutex will be reseted. I want to have a concurrent Reads and only one write access like RwLock but for multiple threads.
In C++ I can actually just refer using pointer and make sure from logic that threads have read only access.
How can I implement this with Rust ? I couldn't find any relevant information about this problem in documentation. RwLock is fine but it's not working with multiple threads.
Wow! thanks, its worked.
Also what does mean Sized here RwLock<T: ?Sized> ? Should I implement that trait for my structure in order to use it with RwLock ?
The ?Sized bound actually makes RwLock able to accept more types than it would otherwise. For example, you could put a trait object inside a RwLock. By default, generic parameters have a Sized bound, and adding T: ?Sized removes that.
Hey, if you indeed statically now that readers and the writer do not exist simultaneously, then you can probably use crossbeam crate and avoid any explicit synchronization and interior mutability:
Unfortunately that won't work: A thread holding an &mut T reference cannot exist at the same time as a thread holding an &T reference to the same data. So you either need separate scopes like in @matklad's example (which forces the writing thread to exit before the reading threads start), or an RwLock to synchronize the threads.