You are viewing a single thread.
View all comments View context
4 points

I kind of disagree here. .lock() has the following behavior:

  • panic() if the lock is already held by this thread - should never happen
  • error - if the current lock holder paniced

The second case is incredibly rare, so it’s one of the few cases where I think .unwrap() makes sense in production code. But it should be an option to handle it in robust code that should never go down. This is rare, but it’s not so rare that we should force all locks to exist in a context where we can recover from panics.

.try_unlock() should never exist because there should only be one way to release a lock: drop(). Having a way to maybe unlock a mutex adds a ton of issues. If we assume this was a typo, .try_lock() absolutely exists, and it’s for a non-blocking lock.

permalink
report
parent
reply
0 points

try_lock already exists; it’s called lock. I just want a more convenient name and I want the name of the new method to be lock, but that ship has sailed.

permalink
report
parent
reply
3 points
*

if you’re really that bothered…

use std::sync::{Mutex, MutexGuard};

trait ULock<'a> {
    type Guard;
    fn ulock(&'a self) -> Self::Guard;
}

impl<'a, T: 'a> ULock<'a> for Mutex<T> {
    type Guard = MutexGuard<'a, T>;
    fn ulock(&'a self) -> Self::Guard {
      self.lock().unwrap()
    }
}

or use a wrapper struct, if you really really want the method to be called exactly lock.

permalink
report
parent
reply
1 point
*

I think a better solution would be to add a method called something like ulock that does a combined lock and unwrap.

My concern with lock+unwrap is only partly because of convenience; I also didn’t like it because I think it’s a bad idea to get people used to casually calling unwrap, because it tends to hide inadequate error handing.

Now that I think about it, I don’t like how unwrap can signal either “I know this can’t fail”, “the possible error states are too rare to care about” or “I can’t be bothered with real error handing right now”. In one or two of those cases you want to leave it in my production code, and in the last you want to audit all instances and replace them with proper error handing. Using the same function for all three cases makes that difficult.

permalink
report
parent
reply

Rust

!rust@programming.dev

Create post

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

!performance@programming.dev

Credits
  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

Community stats

  • 598

    Monthly active users

  • 775

    Posts

  • 3.3K

    Comments