Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Are nested lock recommended? #453

Closed
siddharthteli12 opened this issue Dec 19, 2024 · 3 comments
Closed

Are nested lock recommended? #453

siddharthteli12 opened this issue Dec 19, 2024 · 3 comments

Comments

@siddharthteli12
Copy link

struct Outer {
    map: Arc<RwLock<HashMap<String, Inner>>>,
}

struct Inner {
    inner_map: RwLock<HashMap<String, String>>,
}
impl Outer {
    fn add(&self, key: String, val: String) {
        self.map
            .read()
            .get("test")
            .unwrap()
            .inner_map
            .write()
            .insert(key, val);
    }
}
  • Does this code snippet make any sense.
  • Will it provide any benefit in performance over single RwLock
  • Is it ok to acquire read lock on outer and write lock on inner RwLock
  • How is concurrency handled in this scenario?
  • I could feel this code is susceptible to deadlocks. But still is there any use case for this pattern or its completely useless?
  • Any resource to learn more about locks?
@Amanieu
Copy link
Owner

Amanieu commented Dec 20, 2024

Yes this is perfectly reasonable. You will get a performance benefit if the outer lock is rarely used in write mode.

You can't get a deadlock with this as long as you don't try to acquire the outer lock while holding an inner lock.

@siddharthteli12
Copy link
Author

@Amanieu , Thanks a lot for your response. My main query is how concurrency is being handled in the above scenario.

@Amanieu
Copy link
Owner

Amanieu commented Dec 25, 2024

Exactly how you would expect it to: multiple threads can acquire a read on the outer lock then different threads can acquire a write on the inner locks concurrently.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants