Wrapping tokio::net::TcpStream in Arc<Mutex<TcpStream>>

Hi, I have a 3rd party API which take in a tokio::net::tcpstream which I would like to send back any error occur from the API if any, understand that tokio::net::tcpstream does not have copy trait hence I ended up wrapping it with Arc plus mutex. However, I having difficulties in getting back the tcpstream. This is my current uncompilable code:

loop {
    let (stream, addr) = listener.accept().await?;
    let stream_share = Arc::new(Mutex::new(stream));
    tokio::spawn(async move {
        let stream_clone = stream_share.clone();
        if let Err(e) = processAPI(param1, stream_clone.lock().await, param3).await {
                println!("an error occurred; error = {:?}", e);
                //would like to send back the error 
                //let error_stream = stream_share.clone()
                //....
        }
    });
}

The compilation error for above: expected struct tokio::net::TcpStream, found struct tokio::sync::MutexGuard

if i deref; i.e *(stream_clone.lock().await), the error is: cannot move out of dereference of tokio::sync::MutexGuard<'_, tokio::net::TcpStream> (move occurs because value has type tokio::net::TcpStream, which does not implement the Copy trait)

Would really appreciate if anyone can help me out. Thanks!

In my experience, wrapping a socket in an Arc/Mutex is always a mistake. What are you trying to do this for? You may be able to pass a mutable reference to the socket to the API?

Hi alice, I want to send back any error from the 3rd party API (processAPI) using the same tokio::net::TcpStream which I am unable to as the value is already move when i pass it into the processAPI, hence I thought I would need to wrap it in Arc/Mutex. Below is the 3rd party API function signature (omitted some param types)

async fn processAPI(param1, stream: tokio::net::TcpStream, param3) -> Result<(), Box<dyn std::error::Error>> 

Unfortunately, I am unable to alter the 3rd party API, is there any ways to achieve what I want? Thanks

If it takes ownership of the TcpStream, there is no way to keep it unless the API gives it back to you.

1 Like

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.