Design Bounded Blocking Queue — LeetCode 1188 Python Solution
MediumLeetCode PremiumConcurrency
- Problem
- #1188
- Reading time
- 5 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- 1
- Output
- [1,0,2,2]
- Explanation
- Number of producer threads = 1
Python solution
Python
from threading import Semaphore
class BoundedBlockingQueue(object):
def __init__(self, capacity: int):
self.s1 = Semaphore(capacity)
self.s2 = Semaphore(0)
self.q = deque()
def enqueue(self, element: int) -> None:
self.s1.acquire()
self.q.append(element)
self.s2.release()
def dequeue(self) -> int:
self.s2.acquire()
ans = self.q.popleft()
self.s1.release()
return ans
def size(self) -> int:
return len(self.q)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) to O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 1188. Design Bounded Blocking Queue?
- LeetCode 1188. Design Bounded Blocking Queue is rated Medium on LeetCode.
- What topics does LeetCode 1188. Design Bounded Blocking Queue cover?
- LeetCode 1188. Design Bounded Blocking Queue is tagged Concurrency on LeetCode.
- Is LeetCode 1188. Design Bounded Blocking Queue a premium problem?
- Yes. LeetCode 1188. Design Bounded Blocking Queue is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.