DEV Community


Posted on • Updated on

Python queue.Queue

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

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()
>>> foo
b = q.get()
>>> 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()
Enter fullscreen mode Exit fullscreen mode

If queue is full, no free slow, put() will block while available

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)