A question about thread ownership and lock granularity

I am a novice to multithreaded programming, So bear with me.

I have decided that using a RwLock<HashMap<T, Vec<T>> Is not optimal for my use case. Therefore, I have decided to try HashMap<T,<RwLock<Vec<T>>>

However, The threads still need to have ownership to the HashMap. But I'm not sure how to solve this without putting a lock on the HashMap, Which would make using the RwLock<Vec> useless.

(EDIT) When I mean ownership, I mean mutable/writable ownership.

Any ideas?

What's your use case and why have you decided that RwLock<HashMap<T, Vec<T>> is not optimal for it?

I want multiple threads to access and write to multiple Vecs

If the threads only need to grab a couple vecs at the beginning of their work there's nothing wrong with also wrapping the hash map in a lock. You probably also need to wrap the inner RwLock<Vec> in an Arc so you can clone the Arc and then surrender the outer lock before starting the thread's work.

If the threads never need to mutate the map itself (to add or remove vecs) you can just add an Arc on the HashMap instead of another RwLock.

Do you mean "mutable access" when you say ownership? Because locks don't give you ownership, they only allow you to get mutable access from a shared reference.

That's not true, you can have the outer RwLock which is locked for writes when inserting/removing from the HashMap and for reads when you want to only access the Vecs. If you want to mutate the inner Vecs then you can lock the outer RwLock for reads and the inner RwLock for writes, thus allowing multiple threads to access different Vecs at the same time. The only problem with this approach however is that the threads that want to insert/remove from the HashMap may starve depending to the OS RwLock's policy.

In the end, I would suggest you to use a concurrent hashmap, for example dashmap.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.