RwLock patterns

struct A
{
      map : RwLock<HashMap<K, V>>
}

I understand the semantics of using RwLock. This is what I want to accomplish:

I want to grab read lock, get a reference to value given a key, and then release the lock and then use the value. With the Rust RwLock semantics I need to use the value returned under the read lock. The goal for the lock here is to protect the map not the individual entries returned from the map. How can I accomplish that? Is that even possible?

For instance in Java I can do the following:

MyValue value  = null;
rwLock.readLock().lock()
try
{
    value = map.get("key");
}
finally
{
    rwLock.readLock().unlock();
}
// use MyValue here
value.doSomething();

Can I do this in Rust? If so any pointers will be appreciated.

No, it isn't. More precisely, it would not be sound. It would allow other threads to lock the map, even for writing, which would lead to a race condition.

Since you are comparing this to Java, I'm assuming you would be OK with storing Arc in the hash map and cloning it, instead of storing the values directly?

2 Likes

It's possible only if the map contains references to the values: Rust Playground

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.