Here is an implementation of a simple channel from the book Atomics and Locks:
use std::{
collections::VecDeque,
sync::{Condvar, Mutex},
};
pub struct Channel<T> {
queue: Mutex<VecDeque<T>>,
items: Condvar,
}
impl<T> Channel<T> {
pub fn new() -> Self {
Channel {
queue: Mutex::new(VecDeque::new()),
items: Condvar::new(),
}
}
pub fn send(&self, t: T) {
let mut queue = self.queue.lock().unwrap();
queue.push_back(t);
self.items.notify_one();
}
pub fn receive(&self) -> Option<T> {
let mut queue = self.queue.lock().unwrap();
loop {
if let Some(t) = queue.pop_front() {
return Some(t);
}
queue = self.items.wait(queue).unwrap();
}
}
}
The deadlock occurs if the receive
method is called before the send
method.
I tried to fix it, but I don't see any good way to do this.
I hope someone can help me with this.