Let's look at a very simple example.
1 #Coding:utf82 ImportQueue3 #queue is the meaning of queues4Q=queue.queue (maxsize=10)5 #Create a Queue object6 forIinchRange (9):7 q.put (i)8 #put element9 while notQ.empty ():#detects if an element is emptyTen PrintQ.get (),#reading elements One #default is FIFO
If you need an infinitely long or advanced post-out queue
1 # Create an infinitely long queue, if maxsize less than 1 means that the queue length is infinite. 2 q1=queue.queue ( -1)3#1, the FIFO queue of the Python queueing module is first in, out. Class Queue.queue (maxsize)4#2, LIFO is similar to a heap, i.e. advanced post-out. Class Queue.lifoqueue (maxsize)5#3, there is also a priority queue level lower the more first out. Class Queue.priorityqueue (MaxSize)
Reprint http://www.jb51.net/article/58004.htm
Questions about whether to block and timeout
Official documents:
-
-
Queue.
get
([
block[,
timeout]])
-
Remove and return an item from the queue. If optional args block is true and timeout are None (the default), block if necessary until an item is AV Ailable. If timeout is a positive number, it blocks at most timeout seconds and raises the Empty
exception if no Item is available within that time. Otherwise (block is false), return a item if one is immediately available, else raise the Empty
exception (t Imeout is ignored in this case).
Delete and return an item in the queue. If the optional parameter block is true and timeout is none, it will block until there are no entries in the queue. If block is true and timeout is a positive number (in seconds), then an empty exception is thrown if no items are available within timeout seconds. If the block is false, no matter what the timeout is, an empty exception is thrown if no items are available.
Put usage is similar.
1Q2=queue.queue (3)2 while notQ2.full ():#determine if the Q2 queue is full3Q2.put ('Hello')4 PrintQ2.get (Block=true, timeout=1)5 PrintQ2.get (Block=true, timeout=1)6 PrintQ2.get (Block=true, timeout=1)7 PrintQ2.get (Block=true, timeout=7)8 9 " "Ten Hello One Hello A Hello - exception thrown after seven seconds - Traceback (most recent): the File "queuetext.py", line A, in <module> - Print Q2.get (block=true, timeout=7) - File "C:\Python27\lib\Queue.py", line 176, in Get - Raise Empty + " " - #same as before, change the last sentence to + PrintQ2.get (Block=true, timeout=None) A " " at Hello - Hello - " " - #same as before, change the last sentence to - PrintQ2.get (Block=false, timeout=7) - " " in Hello - Hello to Hello + throw an exception immediately - Traceback (most recent): the File "queuetext.py", line A, in <module> * Print Q2.get (block=true, timeout=7) $ File "C:\Python27\lib\Queue.py", line 176, in GetPanax Notoginseng Raise Empty - " "
-
Queue.
get_nowait
()
-
Equivalent to get(False)
.
Python Queue module