Skip to content

Add Mutex and RwLock APIs for accessing values within a function scope #497

Closed
@EFanZh

Description

@EFanZh

Proposal

Problem statement

This is a follow-up on #485 to add a set of more generalized APIs for accessing values inside lock objects.

Motivating examples or use cases

The most common pattern to access the value inside a lock object is:

  1. Acquire a lock guard object from the lock object.
  2. Access the value through the lock guard object.
  3. Release the lock by dropping the lock guard object.

A problem is that the dropping of lock guards is often implicit, the scope where the lock object being held is not visually apparent, increasing the risk of locks being held for longer than necessary. For example in the code below, uses may not always realize that the mutex_1 is unlocked after the mutex_2.

let mut guard_1 = mutex_1.lock().unwrap();

// Use `guard_1`.

let mut guard_2 = mutex_2.lock().unwrap();

// Use `guard_2`.

// Implicit drop of `guard_2`.
// Implicit drop of `guard_1`.

Not only guard_1 is held longer than necessary, also if some other thread acquire these Mutexs in a different order, deadlock could happen.

Solution sketch

Add the following APIs to the standard library.

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)),
        }
    }
}

With the proposed APIs above, the original example can be rewritten as:

mutex_1.with_mut(|value_1| { ... }).unwrap();
mutex_2.with_mut(|value_2| { ... }).unwrap();

In this way, the scope where the lock being held is more clear to user.

Alternatives

None.

Links and related work

This proposal is originally from: rust-lang/rust#133407 (comment).

What happens now?

This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.

Possible responses

The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):

  • We think this problem seems worth solving, and the standard library might be the right place to solve it.
  • We think that this probably doesn't belong in the standard library.

Second, if there's a concrete solution:

  • We think this specific solution looks roughly right, approved, you or someone else should implement this. (Further review will still happen on the subsequent implementation PR.)
  • We're not sure this is the right solution, and the alternatives or other materials don't give us enough information to be sure about that. Here are some questions we have that aren't answered, or rough ideas about alternatives we'd want to see discussed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    ACP-acceptedAPI Change Proposal is accepted (seconded with no objections)T-libs-apiapi-change-proposalA proposal to add or alter unstable APIs in the standard libraries

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions