How would you refactor this code to use std's Mutex instead of Tokio's mutex

72 points SnooMacaroons3057

Edit: Changed image to show the function calling the alert message.

Hi, I am trying to replace all tokio::sync::Mutex with std::sync::Mutex. But this is kinda getting in the way. How would I refactor this to make it work okay with std's mutex?

Socket is a SplitSink for every connected websocket connection. This function is used to send them an alert message. This method is called from inside a tokio::task::spawn, which is listening for new messages

Send alert method with tokio Mutex-

pub async fn send_alert(socket: Socket, message: &str) {
  socket
    .lock()
    .await
    .send(Message::Text(
        json!({
            "type": "Alert",
            "message":message.to_owned()
        })
        .to_string(),
    ))
    .await
    .unwrap();
}

tokio::task::spawn with tokio mutex. Causes issues when I switch over to the std::sync::Mutex \-

tokio::task::spawn(async move {
  while let Some(request) = rx.recv().await {
     match request.action {
          WsActions::FriendRequestConfirmed(username) => {
              AlertMessage::send_alert(
                  socket.clone(),
                  &format!("{} accepted your friend request", username),
             )
             .await;
          }
          _ => {
                println!("Other action...");
          }
      }    
   }
  // Causing issues 👇🏻 Says - socket is used across await keyword 
  // (which is not `Send`)
  socket.lock().await.close().await.unwrap();
});

For old.reddit users -

https://preview.redd.it/njmfpeyj21j91.png?width=1914&format=png&auto=webp&s=f1763d07be083bae976fea7b755690502144f60d

https://preview.redd.it/bkzlt06wk1j91.png?width=1830&format=png&auto=webp&s=76305a6c33e13196a783a79bd42d6bc027809d7d