Mutex

Struct Mutex 

Source
pub struct Mutex<T> { /* private fields */ }
Expand description

A tracked mutex that automatically records contention metrics and integrates with deadlock detection.

This is a drop-in replacement for tokio::sync::Mutex with additional observability features.

§Example

use async_inspect::sync::Mutex;

#[tokio::main]
async fn main() {
    let mutex = Mutex::new(0, "counter");

    // Spawn multiple tasks that contend for the lock
    let mutex = std::sync::Arc::new(mutex);
    let mut handles = vec![];

    for i in 0..10 {
        let m = mutex.clone();
        handles.push(tokio::spawn(async move {
            let mut guard = m.lock().await;
            *guard += 1;
        }));
    }

    for h in handles {
        h.await.unwrap();
    }

    // Check contention metrics
    let metrics = mutex.metrics();
    println!("Total acquisitions: {}", metrics.acquisitions);
    println!("Contentions: {}", metrics.contentions);
    println!("Contention rate: {:.1}%", metrics.contention_rate() * 100.0);
}

Implementations§

Source§

impl<T> Mutex<T>

Source

pub fn new(value: T, name: impl Into<String>) -> Self

Create a new tracked mutex with a name for identification.

§Arguments
  • value - The initial value to protect
  • name - A descriptive name for debugging and metrics
§Example
use async_inspect::sync::Mutex;

let mutex = Mutex::new(vec![1, 2, 3], "shared_vector");
Source

pub async fn lock(&self) -> MutexGuard<'_, T>

Acquire the lock, blocking until it’s available.

This method automatically:

  • Records wait time if there’s contention
  • Notifies the deadlock detector
  • Tracks acquisition metrics
§Example
use async_inspect::sync::Mutex;

let mutex = Mutex::new(42, "my_value");
let guard = mutex.lock().await;
println!("Value: {}", *guard);
Source

pub fn try_lock(&self) -> Option<MutexGuard<'_, T>>

Try to acquire the lock immediately.

Returns None if the lock is already held.

§Example
use async_inspect::sync::Mutex;

let mutex = Mutex::new(42, "my_value");
let result = mutex.try_lock();
if let Some(guard) = result {
    println!("Got the lock: {}", *guard);
} else {
    println!("Lock is held by another task");
}
Source

pub fn metrics(&self) -> LockMetrics

Get the current contention metrics for this mutex.

§Example
use async_inspect::sync::Mutex;

let mutex = Mutex::new(42, "my_value");
// ... some operations ...
let metrics = mutex.metrics();
println!("Acquisitions: {}", metrics.acquisitions);
println!("Contention rate: {:.1}%", metrics.contention_rate() * 100.0);
Source

pub fn reset_metrics(&self)

Reset the contention metrics.

Source

pub fn name(&self) -> &str

Get the name of this mutex.

Source

pub fn resource_id(&self) -> ResourceId

Get the resource ID for deadlock detection.

Source

pub fn into_inner(self) -> T

Consume the mutex and return the inner value.

§Panics

This method will panic if the mutex is poisoned.

Source

pub fn get_mut(&mut self) -> &mut T

Get a mutable reference to the inner value without locking.

This is safe because we have exclusive access via &mut self.

Trait Implementations§

Source§

impl<T: Debug> Debug for Mutex<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T> !Freeze for Mutex<T>

§

impl<T> !RefUnwindSafe for Mutex<T>

§

impl<T> Send for Mutex<T>
where T: Send,

§

impl<T> Sync for Mutex<T>
where T: Send,

§

impl<T> Unpin for Mutex<T>
where T: Unpin,

§

impl<T> !UnwindSafe for Mutex<T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,