Skip to content

Tracking Issue for lock_value_accessors #133407

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

Open
2 of 4 tasks
EFanZh opened this issue Nov 24, 2024 · 9 comments
Open
2 of 4 tasks

Tracking Issue for lock_value_accessors #133407

EFanZh opened this issue Nov 24, 2024 · 9 comments
Labels
C-tracking-issue Category: An issue tracking the progress of sth. like the implementation of an RFC T-libs-api Relevant to the library API team, which will review and decide on the PR/issue.

Comments

@EFanZh
Copy link
Contributor

EFanZh commented Nov 24, 2024

Feature gate: #![feature(lock_value_accessors)]

This is a tracking issue for feature lock_value_accessors.

Public API

impl<T> Mutex<T> {
    pub fn get_cloned(&self) -> Result<T, PoisonError<()>> where T: Clone { ... }
    pub fn set(&self, value: T) -> Result<(), PoisonError<T>> { ... }
    pub fn replace(&self, value: T) -> LockResult<T> { ... }
}

impl<T> RwLock<T> {
    pub fn get_cloned(&self) -> Result<T, PoisonError<()>> where T: Clone { ... }
    pub fn set(&self, value: T) -> Result<(), PoisonError<T>> { ... }
    pub fn replace(&self, value: T) -> LockResult<T> { ... }
}

Steps / History

Unresolved Questions

  • Whether we should checking poisoning first and avoid unnecessary lock acquire attempts.

Footnotes

  1. https://std-dev-guide.rust-lang.org/feature-lifecycle/stabilization.html

@EFanZh EFanZh added C-tracking-issue Category: An issue tracking the progress of sth. like the implementation of an RFC T-libs-api Relevant to the library API team, which will review and decide on the PR/issue. labels Nov 24, 2024
@Noratrieb
Copy link
Member

I think the name get is too generic and "default", it makes you think that this is what you usually want, even if it is often not (as it clones). Certainly a useful method, but I think the clone should be more explicit in the name, I'd suggest get_cloned (maybe someone else has a better name).

@EFanZh
Copy link
Contributor Author

EFanZh commented Nov 24, 2024

I am OK with get_cloned.

@marmeladema
Copy link
Contributor

Would it make sense to have a get_copied()?

Or even a get_with which accepts a closure to retrieve the return value? This could cover clone and copy types as well as allow to return a value from a nested field like mutex.get_with(|val| val.field.clone())

@EFanZh
Copy link
Contributor Author

EFanZh commented Nov 24, 2024

@marmeladema: I am in favor of adding a set of more generalized APIs:

impl<T> Mutex<T>
where
    T: ?Sized,
{
    pub fn with_mut<F, R>(&self, f: F) -> Result<R, PoisonError<F>>
    where
        F: FnOnce(&mut T) -> R,
    {
        match self.lock() {
            Ok(mut guard) => Ok(f(&mut guard)),
            Err(_) => Err(PoisonError::new(f)),
        }
    }
}

impl<T> RwLock<T>
where
    T: ?Sized,
{
    pub fn with<F, R>(&self, f: F) -> Result<R, PoisonError<F>>
    where
        F: FnOnce(&T) -> R,
    {
        match self.read() {
            Ok(guard) => Ok(f(&guard)),
            Err(_) => Err(PoisonError::new(f)),
        }
    }

    pub fn with_mut<F, R>(&self, f: F) -> Result<R, PoisonError<F>>
    where
        F: FnOnce(&mut T) -> R,
    {
        match self.write() {
            Ok(mut guard) => Ok(f(&mut guard)),
            Err(_) => Err(PoisonError::new(f)),
        }
    }
}

These new APIs have the advantage of being explicit about locking scopes. Traditional APIs rely on the destructing of lock guard objects, which is not visually apparent to users, increasing the risk of locks being held for longer than necessary. With the new APIs, the chances of unintentionally holding locks for extended periods can be reduced.

A new ACP has been accepted for non-poisoning types: rust-lang/libs-team#497.

Zalathar added a commit to Zalathar/rust that referenced this issue Dec 15, 2024
…atrieb

Add value accessor methods to `Mutex` and `RwLock`

- ACP: rust-lang/libs-team#485.
- Tracking issue: rust-lang#133407.

This PR adds `get`, `set` and `replace` methods to the `Mutex` and `RwLock` types for quick access to their contained values.

One possible optimization would be to check for poisoning first and return an error immediately, without attempting to acquire the lock. I didn’t implement this because I consider poisoning to be relatively rare, adding this extra check could slow down common use cases.
rust-timer added a commit to rust-lang-ci/rust that referenced this issue Dec 15, 2024
Rollup merge of rust-lang#133406 - EFanZh:lock-value-accessors, r=Noratrieb

Add value accessor methods to `Mutex` and `RwLock`

- ACP: rust-lang/libs-team#485.
- Tracking issue: rust-lang#133407.

This PR adds `get`, `set` and `replace` methods to the `Mutex` and `RwLock` types for quick access to their contained values.

One possible optimization would be to check for poisoning first and return an error immediately, without attempting to acquire the lock. I didn’t implement this because I consider poisoning to be relatively rare, adding this extra check could slow down common use cases.
github-actions bot pushed a commit to tautschnig/verify-rust-std that referenced this issue Mar 11, 2025
…atrieb

Add value accessor methods to `Mutex` and `RwLock`

- ACP: rust-lang/libs-team#485.
- Tracking issue: rust-lang#133407.

This PR adds `get`, `set` and `replace` methods to the `Mutex` and `RwLock` types for quick access to their contained values.

One possible optimization would be to check for poisoning first and return an error immediately, without attempting to acquire the lock. I didn’t implement this because I consider poisoning to be relatively rare, adding this extra check could slow down common use cases.
@arvidfm
Copy link

arvidfm commented May 25, 2025

Sorry if this has been mentioned elsewhere, maybe it's obvious but it wasn't clear to me - is there a reason that get_cloned returns a Result<T, PoisonError<()>> instead of a Result<T, PosionError<T>>? The latter seems like it would better mirror the signature of Mutex::lock, or (and especially) Mutex::into_inner. That is, why not:

pub fn get_cloned(&self) -> Result<T, PoisonError<T>>
where
    T: Clone,
{
    match self.lock() {
        Ok(guard) => Ok((*guard).clone()),
        Err(e) => Err(PoisonError::new((*e.into_inner()).clone())),
    }
}

@EFanZh
Copy link
Contributor Author

EFanZh commented May 25, 2025

@arvidfm: I am not sure that whether calling clone is a good idea on the Err path. In my personal experience, most of the time, users just write mutex.lock().unwrap(), so for get_clone, I assume they will also just write mutex.get_cloned().unwrap(). Introducing a clone() here will unnecessarily increase the overhead for the more common case.

@arvidfm
Copy link

arvidfm commented May 25, 2025

@EFanZh Is it worth optimising for that case, considering that the user was already prepared to pay the cost of the clone to begin with by calling get_cloned, and the error path is presumably a lot less common?

As it stands, the signature breaks the pattern of get_clone().unwrap_or_else(PoisonError::into_inner) which works for Mutex::lock and Mutex::into_inner, and if the user did want to clone the value regardless of poison status they would need to write something similar to what I proposed above, at which point they're essentially duplicating the functionality of get_cloned.

@EFanZh
Copy link
Contributor Author

EFanZh commented May 26, 2025

@arvidfm: If user want to get the value regardless of the poison status, maybe its better to use the non-poison version? #134645

@arvidfm
Copy link

arvidfm commented May 26, 2025

@EFanZh I could imagine having poison handling in some places, while in other places just wanting to get a copy of the current value regardless. Or perhaps wanting to clone the inner value, but in the case of poisoning wanting to do something to the cloned value before returning it.

I'm not saying I think it's a particularly common use case or anything, I just think that cloning on the error path would make the method more general and more useful for those kinds of edge cases. And to me at least it doesn't seem worth breaking symmetry with other similar methods for the sake of optimising the error path, especially when the optimisation is removing a call that the user already opted into by virtue of calling a cloning method to begin with.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-tracking-issue Category: An issue tracking the progress of sth. like the implementation of an RFC T-libs-api Relevant to the library API team, which will review and decide on the PR/issue.
Projects
None yet
Development

No branches or pull requests

4 participants