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:
- Calling
recv()
on a variable of typempsc::Receiver
needs that the variable is mutatble; - I don't want
Notifier
itself is mutable, so I want to use interior mutation. - I first tried to use
RefCell
but failed due to it doesn't implementsSync
trait which is essential totokio::spawn()
; - I shift to use
Mutex
instead ofRefCell
. - Meets this error..