1115. Print FooBar Alternately
1115. Print FooBar Alternately
Description
Implement a thread-safe bounded blocking queue that has the following methods:
BoundedBlockingQueue(int capacity)The constructor initializes the queue with a maximumcapacity.void enqueue(int element)Adds anelementto 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:
1 | Input: |
Example 2:
1 | Input: |
Constraints:
1 <= Number of Prdoucers <= 81 <= Number of Consumers <= 81 <= size <= 300 <= element <= 20- The number of calls to
enqueueis greater than or equal to the number of calls todequeue. - At most
40calls will be made toenque,deque, andsize.
Hints/Notes
- 2025/03/24 Q2
- concurrency
- No solution from 0x3F or Leetcode
Solution
Language: C++
1 | class FooBar { |