RwLock

Struct RwLock 

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

A tracked read-write lock that automatically records contention metrics and integrates with deadlock detection.

This is a drop-in replacement for tokio::sync::RwLock with additional observability features. It tracks read and write operations separately.

§Example

use async_inspect::sync::RwLock;

#[tokio::main]
async fn main() {
    let lock = RwLock::new(vec![1, 2, 3], "shared_data");

    // Multiple readers can access simultaneously
    let lock = std::sync::Arc::new(lock);
    let mut handles = vec![];

    for i in 0..5 {
        let l = lock.clone();
        handles.push(tokio::spawn(async move {
            let guard = l.read().await;
            println!("Reader {}: {:?}", i, *guard);
        }));
    }

    // Writer has exclusive access
    {
        let mut guard = lock.write().await;
        guard.push(4);
    }

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

    // Check contention metrics
    let (read_metrics, write_metrics) = lock.metrics();
    println!("Read acquisitions: {}", read_metrics.acquisitions);
    println!("Write acquisitions: {}", write_metrics.acquisitions);
}

Implementations§

Source§

impl<T> RwLock<T>

Source

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

Create a new tracked RwLock 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::RwLock;
use std::collections::HashMap;

let lock = RwLock::new(HashMap::<String, i32>::new(), "user_cache");
Source

pub async fn read(&self) -> RwLockReadGuard<'_, T>

Acquire a read lock, blocking until it’s available.

Multiple readers can hold the lock simultaneously, but writers must wait for all readers to release.

§Example
use async_inspect::sync::RwLock;

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

pub async fn write(&self) -> RwLockWriteGuard<'_, T>

Acquire a write lock, blocking until it’s available.

Writers have exclusive access - no other readers or writers can hold the lock simultaneously.

§Example
use async_inspect::sync::RwLock;

let lock = RwLock::new(42, "my_value");
let mut guard = lock.write().await;
*guard = 100;
Source

pub fn try_read(&self) -> Option<RwLockReadGuard<'_, T>>

Try to acquire a read lock immediately.

Returns None if a writer is holding the lock.

Source

pub fn try_write(&self) -> Option<RwLockWriteGuard<'_, T>>

Try to acquire a write lock immediately.

Returns None if any readers or writers are holding the lock.

Source

pub fn metrics(&self) -> (LockMetrics, LockMetrics)

Get the current contention metrics for this RwLock.

Returns a tuple of (read_metrics, write_metrics).

§Example
use async_inspect::sync::RwLock;

let lock = RwLock::new(42, "my_value");
// ... some operations ...
let (read_metrics, write_metrics) = lock.metrics();
println!("Read acquisitions: {}", read_metrics.acquisitions);
println!("Write acquisitions: {}", write_metrics.acquisitions);
Source

pub fn read_metrics(&self) -> LockMetrics

Get only the read metrics.

Source

pub fn write_metrics(&self) -> LockMetrics

Get only the write metrics.

Source

pub fn reset_metrics(&self)

Reset all contention metrics.

Source

pub fn name(&self) -> &str

Get the name of this RwLock.

Source

pub fn resource_id(&self) -> ResourceId

Get the resource ID for deadlock detection.

Source

pub fn into_inner(self) -> T

Consume the RwLock and return the inner value.

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 RwLock<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 RwLock<T>

§

impl<T> !RefUnwindSafe for RwLock<T>

§

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

§

impl<T> Sync for RwLock<T>
where T: Send + Sync,

§

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

§

impl<T> !UnwindSafe for RwLock<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,