forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdesign-bounded-blocking-queue.py
More file actions
43 lines (37 loc) · 931 Bytes
/
design-bounded-blocking-queue.py
File metadata and controls
43 lines (37 loc) · 931 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Time: O(n)
# Space: O(1)
import threading
import collections
class BoundedBlockingQueue(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.__cv = threading.Condition()
self.__q = collections.deque()
self.__cap = capacity
def enqueue(self, element):
"""
:type element: int
:rtype: void
"""
with self.__cv:
while len(self.__q) == self.__cap:
self.__cv.wait()
self.__q.append(element)
self.__cv.notifyAll()
def dequeue(self):
"""
:rtype: int
"""
with self.__cv:
while not self.__q:
self.__cv.wait()
self.__cv.notifyAll()
return self.__q.popleft()
def size(self):
"""
:rtype: int
"""
with self.__cv:
return len(self.__q)