1188. Design Bounded Blocking Queue

Implement a thread-safe bounded blocking queue that has the following methods:

  • BoundedBlockingQueue(int capacity) The constructor initializes the queue with a maximum capacity.
  • void enqueue(int element) Adds an element to the front of the queue. If the queue is full, the calling thread is blocked until the queue is no longer full.
  • int dequeue() Returns the element at the rear of the queue and removes it. If the queue is empty, the calling thread is blocked until the queue is no longer empty.
  • int size() Returns the number of elements currently in the queue.

Your implementation will be tested using multiple threads at the same time. Each thread will either be a producer thread that only makes calls to the enqueue method or a consumer thread that only makes calls to the dequeue method. The size method will be called after every test case.

Please do not use built-in implementations of bounded blocking queue as this will not be accepted in an interview.

 

Example 1:

Input:
1
1
["BoundedBlockingQueue","enqueue","dequeue","dequeue","enqueue","enqueue","enqueue","enqueue","dequeue"]
[[2],[1],[],[],[0],[2],[3],[4],[]]

Output:
[1,0,2,2]

Explanation:
Number of producer threads = 1
Number of consumer threads = 1

BoundedBlockingQueue queue = new BoundedBlockingQueue(2);   // initialize the queue with capacity = 2.

queue.enqueue(1);   // The producer thread enqueues 1 to the queue.
queue.dequeue();    // The consumer thread calls dequeue and returns 1 from the queue.
queue.dequeue();    // Since the queue is empty, the consumer thread is blocked.
queue.enqueue(0);   // The producer thread enqueues 0 to the queue. The consumer thread is unblocked and returns 0 from the queue.
queue.enqueue(2);   // The producer thread enqueues 2 to the queue.
queue.enqueue(3);   // The producer thread enqueues 3 to the queue.
queue.enqueue(4);   // The producer thread is blocked because the queue's capacity (2) is reached.
queue.dequeue();    // The consumer thread returns 2 from the queue. The producer thread is unblocked and enqueues 4 to the queue.
queue.size();       // 2 elements remaining in the queue. size() is always called at the end of each test case.

Example 2:

Input:
3
4
["BoundedBlockingQueue","enqueue","enqueue","enqueue","dequeue","dequeue","dequeue","enqueue"]
[[3],[1],[0],[2],[],[],[],[3]]
Output:
[1,0,2,1]

Explanation:
Number of producer threads = 3
Number of consumer threads = 4

BoundedBlockingQueue queue = new BoundedBlockingQueue(3);   // initialize the queue with capacity = 3.

queue.enqueue(1);   // Producer thread P1 enqueues 1 to the queue.
queue.enqueue(0);   // Producer thread P2 enqueues 0 to the queue.
queue.enqueue(2);   // Producer thread P3 enqueues 2 to the queue.
queue.dequeue();    // Consumer thread C1 calls dequeue.
queue.dequeue();    // Consumer thread C2 calls dequeue.
queue.dequeue();    // Consumer thread C3 calls dequeue.
queue.enqueue(3);   // One of the producer threads enqueues 3 to the queue.
queue.size();       // 1 element remaining in the queue.

Since the number of threads for producer/consumer is greater than 1, we do not know how the threads will be scheduled in the operating system, even though the input seems to imply the ordering. Therefore, any of the output [1,0,2] or [1,2,0] or [0,1,2] or [0,2,1] or [2,0,1] or [2,1,0] will be accepted.

 

Constraints:

  • 1 <= Number of Prdoucers <= 8
  • 1 <= Number of Consumers <= 8
  • 1 <= size <= 30
  • 0 <= element <= 20
  • The number of calls to enqueue is greater than or equal to the number of calls to dequeue.
  • At most 40 calls will be made to enque, deque, and size.

1188. Design Bounded Blocking Queue
use std::collections::VecDeque;
use std::sync::Condvar;
use std::sync::Mutex;

struct BoundedBlockingQueue {
    queue: (Mutex<VecDeque<i32>>, Condvar),
    capacity: usize,
}

impl BoundedBlockingQueue {
    fn new(capacity: usize) -> Self {
        let queue = (Mutex::new(VecDeque::new()), Condvar::new());
        BoundedBlockingQueue { queue, capacity }
    }

    fn enqueue(&self, element: i32) {
        let (lock, cvar) = &self.queue;
        let mut g = cvar
            .wait_while(lock.lock().unwrap(), |queue| queue.len() == self.capacity)
            .unwrap();
        g.push_back(element);
        cvar.notify_all();
    }

    fn dequeue(&self) -> i32 {
        let (lock, cvar) = &self.queue;
        let mut g = cvar
            .wait_while(lock.lock().unwrap(), |queue| queue.is_empty())
            .unwrap();
        let res = g.pop_front().unwrap();
        cvar.notify_all();
        res
    }

    fn size(&self) -> i32 {
        let (lock, _cvar) = &self.queue;
        let g = lock.lock().unwrap();
        g.len() as i32
    }
}

#[derive(Debug)]
enum TestCommand {
    Enqueue(i32),
    Dequeue,
}

impl TestCommand {
    fn is_enqueue(&self) -> bool {
        use TestCommand::*;
        match self {
            Enqueue(_) => true,
            Dequeue => false,
        }
    }
    fn is_dequeue(&self) -> bool {
        use TestCommand::*;
        match self {
            Enqueue(_) => false,
            Dequeue => true,
        }
    }
}

fn test_case(
    n_producer: usize,
    n_consumer: usize,
    capacity: usize,
    test_cmds: VecDeque<TestCommand>,
) -> Vec<i32> {
    use std::sync::mpsc::channel;
    use std::sync::Arc;
    use threadpool::ThreadPool;
    use TestCommand::*;

    let (tx, rx) = channel();
    let bbq: Arc<BoundedBlockingQueue> = Arc::new(BoundedBlockingQueue::new(capacity));
    let producer_pool = ThreadPool::new(n_producer);
    let consumer_pool = ThreadPool::new(n_consumer);

    for test_cmd in test_cmds {
        let bbq = bbq.clone();
        let tx = tx.clone();
        match test_cmd {
            Enqueue(x) => producer_pool.execute(move || {
                bbq.enqueue(x);
            }),
            Dequeue => consumer_pool.execute(move || {
                let y = bbq.dequeue();
                tx.send(y).unwrap();
            }),
        }
    }
    producer_pool.join();
    consumer_pool.join();
    tx.send(bbq.size()).unwrap();
    let res: Vec<i32> = rx.try_iter().collect();
    res
}

#[test]
fn test() {
    use TestCommand::*;

    let n_producer = 1;
    let n_consumer = 1;
    let cmds = vec_string![
        "BoundedBlockingQueue",
        "enqueue",
        "dequeue",
        "dequeue",
        "enqueue",
        "enqueue",
        "enqueue",
        "enqueue",
        "dequeue"
    ];
    let args = vec_vec_i32![[2], [1], [], [], [0], [2], [3], [4], []];
    let ans = vec![1, 0, 2, 2];
    let capacity = args[0][0] as usize;
    let mut test_cmds: VecDeque<TestCommand> = VecDeque::new();
    for i in 1..cmds.len() {
        if cmds[i] == "enqueue" {
            test_cmds.push_back(Enqueue(args[i][0]));
        }
        if cmds[i] == "dequeue" {
            test_cmds.push_back(Dequeue);
        }
    }
    let res = test_case(n_producer, n_consumer, capacity, test_cmds);
    assert_eq!(res, ans);

    let n_producer = 3;
    let n_consumer = 4;
    let cmds = vec_string![
        "BoundedBlockingQueue",
        "enqueue",
        "enqueue",
        "enqueue",
        "dequeue",
        "dequeue",
        "dequeue",
        "enqueue"
    ];
    let args = vec_vec_i32![[3], [1], [0], [2], [], [], [], [3]];
    let capacity = args[0][0] as usize;
    let mut test_cmds: VecDeque<TestCommand> = VecDeque::new();
    for i in 1..cmds.len() {
        if cmds[i] == "enqueue" {
            test_cmds.push_back(Enqueue(args[i][0]));
        }
        if cmds[i] == "dequeue" {
            test_cmds.push_back(Dequeue);
        }
    }
    let res = test_case(n_producer, n_consumer, capacity, test_cmds);
    assert_eq!(res.len(), 4);
    assert_eq!(res[3], 1);
}