Mutex Try Lock Skips Waiting

Probe a held std::sync::Mutex with try_lock, match TryLockError::WouldBlock, then acquire it normally after the guard drops.

RustResilience

Code

rustsnippet
29 lines
use std::sync::{Mutex, TryLockError};

fn main() {
    let mutex = Mutex::new(0);

    {
        let mut guard = mutex.lock().unwrap();
        *guard += 1;

        // try_lock reports WouldBlock instead of waiting for the guard
        match mutex.try_lock() {
            Ok(_) => println!("unexpected second guard"),
            Err(TryLockError::WouldBlock) => println!("would block: lock is held"),
            Err(TryLockError::Poisoned(error)) => println!("poisoned: {error}"),
        }
        println!("counter under guard: {}", *guard);
    }

    // after the guard drops the same lock can be acquired again
    match mutex.try_lock() {
        Ok(mut guard) => {
            *guard += 1;
            println!("second increment: {}", *guard);
        }
        Err(error) => println!("try_lock failed: {error}"),
    }

    println!("final: {}", *mutex.lock().unwrap());
}

Inside the snippet

Mutex Try Lock Skips Waiting comes down to the function main.

A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

Caveats

  • No third-party code is loaded at any point while this runs.

Using it

Entry signature: fn main()

The run emits 3 labeled sections — unexpected second guard, would block: lock is held, poisoned: — one per step.

Key statements

Ok(mut guard) => {
*guard += 1;
println!("second increment: {}", *guard);
}
let mut guard = mutex.lock().unwrap();
match mutex.try_lock() {
Ok(_) => println!("unexpected second guard"),
Err(TryLockError::WouldBlock) => println!("would block: lock is held"),
Err(TryLockError::Poisoned(error)) => println!("poisoned: {error}"),
}

Interactive Tools for This Topic

FAQ

What does Mutex Try Lock Skips Waiting print when run?
Execute the whole file; each printed line is prefixed with a label like `unexpected second guard`, `would block: lock is held`, `poisoned:`.