How to print data inside a tokio::sync::RwLock?

use tokio::sync::RwLock;
use std::fmt;


struct Locker{
    data: RwLock<Vec<i8>>,
}

impl fmt::Debug for Locker{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result{
        f.debug_struct("Locker")
            .field("data", &self.data)
            .finish()
    }
}

#[tokio::main]
async fn main(){
    let locker = Locker{
        data: RwLock::new(Vec::new()),
    };
    let mut data = locker.data.write().await;
    data.push(1);
    println!("{:?}", locker)
}

I implement Debug trait for Locker, but how the software output data of Vec insideRwLock?

The Debug impl needs to take a read lock to access the inner data. But tokio's RwLock returns a Future, so it would have to be polled in a synchronous function.

It can be done, but all kinds of bad things could happen if you tried.

Instead, I would make sure the inner data implements Debug (in this case it does) and then print its contents wherever you have already acquired a lock.

1 Like

You can call RwLock::try_read to take a read lock if its currently free. If that fails, just print <locked>. This is similar to what the standard library does for mutex. (src)

Don't try to block on taking the lock. You don't want println statements to deadlock your code. (That's what would happen in your snippet because you're still holding data when you print.)

2 Likes

Yes, this is what I want, :+1:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.