Create a "queue" object
Import Queue
Q = queue.queue (maxsize = 10)
The Queue.queue class is a synchronous implementation of a queue. The queue length can be unlimited or limited. The queue length can be set through the optional parameter maxsize of the queue's constructor. If MaxSize is less than 1, it means that the queue length is infinite.
Put a value in the queue
Q.put (10)
The put () method of the call queue object inserts an item at the end of the team. Put () has two parameters, the first item is required, the value of the inserted item, and the second block is an optional parameter, which defaults to
1. If the queue is currently empty and the Block is the 1,put () method, the calling thread pauses until a data cell is vacated. If the block is the 0,put method, the full exception is thrown.
Take a value out of the queue
Q.get ()
The Get () method of the call queue object is removed from the team header and returns an item. The optional parameter is block, which is true by default. If the queue is empty and the Block is True,get (), the calling thread is paused until a project is available. If the queue is empty and the block is false, the queue throws an empty exception.
The Python queue module has three types of queues and constructors:
1, the Python queue module FIFO queuing first-out. Class queue. Queue (maxsize)
2, LIFO similar to the heap, that is, advanced after out. Class queue. Lifoqueue (maxsize)
3, there is a priority queue level lower the more first out. Class queue. Priorityqueue (maxsize)
Common methods in this package (q = Queue.queue ()):
Q.qsize () returns the size of the queue
Q.empty () returns True if the queue is empty, and vice versa false
Q.full () returns True if the queue is full, otherwise false
Q.full corresponds to maxsize size
Q.get ([block[, timeout]]) Get queue, timeout wait time
Q.get_nowait () quite q.get (False)
Non-blocking Q.put (item) write queue, timeout wait time
Q.put_nowait (item) quite Q.put (item, False)
Q.task_done () After completing a work, the Q.task_done () function sends a signal to the queue that the task has completed
Q.join () actually means waiting until the queue is empty before performing another operation
List can be used to achieve the role of the queue, why also have a queue?
Because the elements of a list in multiple threads can be taken at the same time to be unsafe, the queue cannot be taken at the same time.
Instance:
ImportThreading,queue fromTimeImportSleep fromRandomImportRandintclassProduction (Threading. Thread):defRun (self): whileTrue:r=randint (0,100) Q.put (R)Print("production out of the%s bun"%r) Sleep (1)classProces (Threading. Thread):defRun (self): whileTrue:re=Q.get ()Print("eat the%s # Bun"%re)if __name__=="__main__": Q=queue. Queue (10) Threads=[Production (), Production (), Production (), Proces ()] forTinchThreads:t.start ()
Python Threading's queue