Why my producer-consumer code stuck?

I tried to implement a cocurrently-shared queue support multi-readr and multi-writer, with the a Mutex wrapped VecDeque, a Condvar for readers and one for writers. However, after sometimes they stuck, and I cannot figure out why.
core struct:

struct Queue {
    queue: Mutex<VecDeque<i32>>,
    capacity: usize,
    writer_cond: Condvar,
    reader_cond: Condvar,
}

impl Queue {
    fn new(capacity: usize) -> Self {
        Queue {
            queue: Mutex::new(VecDeque::new()),
            capacity: capacity,
            writer_cond: Condvar::new(),
            reader_cond: Condvar::new(),
        }
    }
    fn produce(&self, i: i32) {
        let guard = self.queue.lock().unwrap();
        let mut buffer = self
            .writer_cond
            .wait_while(guard, |q| q.len() == self.capacity)
            .unwrap();
        buffer.push_back(i);
        drop(buffer);
        self.reader_cond.notify_one();
    }

    fn consume(&self) -> i32 {
        let guard = self.queue.lock().unwrap();
        let mut buffer = self
            .writer_cond
            .wait_while(guard, |q| q.is_empty())
            .unwrap();
        let result = buffer.pop_front();
        drop(buffer);
        self.writer_cond.notify_one();
        result.unwrap()
    }
}

playground

I believe you have a typo there, both end wait on the writer_cond while the reader_cond is not waited by anyone.

2 Likes

Oh my. I didn't find the rookie mistake although I debugged for half an hour. :rofl:

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.