Python has 3 ways to implement a "queue" (FIFO rule).
- list
- collections.deque
- queue.Queue
list is build-in, multi purpose structure. If get item out from a list, need to shift all item, may slow. collections.deque: list-like container with fast appends and pops on either end. Here introduce more about Queue:
from queue import Queue
q = Queue(5) # 5 is maxsize of the queue [1]
q.put('foo') # put item into a queue
q.put('bar')
print(q.qsize()) # approximate [2] size of the queue
>>> 2
print(q.full()) # check full or not
>>> False
print(q.empty()) # check empty or not
>>> False
a = q.get()
print(a)
>>> foo
b = q.get()
print(b)
>>> bar
c = q.get()
# blocking ... queue is empty, wait until an item is available.
get_nowait() # get(False), if not available, raise queue.Empty
# blocking process
task_done() & join()
[1]
If queue is full, no free slow, put() will block while available
[2]
qsize() > 0 doesnβt guarantee that a subsequent get() will not block, nor will qsize() < maxsize guarantee that put() will not block.
Top comments (0)