Implement the producer and consumer model (instance description) by using the Queue instance description
In Python, a queue is the most common form of data exchange between threads.
The Python Queue module has three queues and constructor functions:
1. The first-in-first-out Queue of the Python Queue module. Class Queue. Queue (maxsize)
2. LIFO is similar to heap, that is, first and then output. Class Queue. LifoQueue (maxsize)
3. The lower the priority queue level, the more advanced it is. Class Queue. PriorityQueue (maxsize)
Common methods in this package (q = Queue. Queue ()):
Q. qsize () returns the size of the queue.
Q. empty (): If the queue is empty, True is returned. Otherwise, False is returned.
Q. full () if the queue is full, True is returned; otherwise, False is returned.
Q. full corresponds to maxsize
Q. get ([block [, timeout]) get the queue and timeout wait time
Q. get_nowait () is equivalent to q. get (False)
Non-blocking q. put (item) Write queue, timeout wait time
Q. put_nowait (item) is equivalent to q. put (item, False)
Q. After task_done () completes a job, the q. task_done () function sends a signal to the completed queue of the job.
Q. join () actually means that when the queue is empty, other operations will be performed.
# Coding = utf-8import Queueimport threadingimport timeq = Queue. queue (maxsize = 10) # create a Queue object with a length limit of 10. If maxsize is smaller than 1, it means unlimited def producer (name): count = 1 while True: q. put (count) # put the value into the queue. The default block is True. When no data is available, the call thread is paused. Otherwise, an exception is thrown. print "% s produces Steamed Stuffed Bun % d" % (name, count) count + = 1 time. sleep (0.5) def consumer (name): while True: conut_con = q. get () # The default block value from the queue is True. When no data exists, the call thread is paused. Otherwise, an exception is thrown. print "% s has eaten the Steamed Stuffed Bun % d" % (name, conut_con) time. sleep (2) pro = threading. thread (target = producer, args = ("",) con = threading. thread (target = consumer, args = ("xu",) con2 = threading. thread (target = consumer, args = ("sx",) pro. start () con. start () con2.start () # enable the thread
The above Queue Implementation of the producer and consumer model (instance description) is all the content shared by Alibaba Cloud. I hope you can give us a reference and support for the customer's home.