Help, future is not 'Send', how to fix

This is my test code:

use std::sync::Mutex;
use tokio::sync::mpsc;

struct Notifier {
    data: Mutex<mpsc::Receiver<u32>>,
}

impl Notifier {
    fn new(rx: mpsc::Receiver<u32>) -> Self {
        Self {
            data: Mutex::new(rx),
        }
    }

    async fn wait(&self) -> u32 {
        let mut guard = self.data.lock().unwrap();
        if let Some(v) = guard.recv().await {
            return v;
        }
        0
    }
}

#[tokio::main]
async fn main() {
    let (tx, rx) = mpsc::channel(10);
    tokio::spawn(async {
        let notifier = Notifier::new(rx);
        let d = notifier.wait().await;
    });

    tx.send(5);
}

The reason is simple and obvious: the guard is instantly dropped when it reaches the end of the function and it is not Send.

What I want to know is how to fix this error...

The mutex here seems redundant. But it is the result of a chain of errors:

  1. Calling recv() on a variable of type mpsc::Receiver needs that the variable is mutatble;
  2. I don't want Notifier itself is mutable, so I want to use interior mutation.
  3. I first tried to use RefCell but failed due to it doesn't implements Sync trait which is essential to tokio::spawn();
  4. I shift to use Mutex instead of RefCell.
  5. Meets this error..

I'm not 100% sure, but you might want to read https://tokio-rs.github.io/tokio/doc/tokio/sync/struct.Mutex.html and see if that can solve the problem.

1 Like

Exactly, tokio::sync::Mutex - Rust works.

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.