Python Queue Module Detailed

Source: Internet
Author: User
In Python, queues are the most common form of exchanging data between threads. The queue module is a module that provides queued operations, although it's easy to use, but if you're not careful, there are some surprises.

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

Example:
Implement a thread that constantly generates a random number into a queue (consider using the queue this module)
Implement a thread that constantly takes out an odd number from the top of the queue
Implement another thread to continuously remove even numbers from the queue above

#!/usr/bin/env python#coding:utf8import random,threading,timefrom Queue import queue#producer threadclass Producer ( Threading. Thread): Def __init__ (self, T_name, queue): Threading. thread.__init__ (self,name=t_name) Self.data=queue def run (self): For I in range: #随机产生10个数字, can be modified to any size RA       Ndomnum=random.randint (1,99) print "%s:%s is producing%d to the queue!"% (Time.ctime (), Self.getname (), Randomnum) Self.data.put (Randomnum) #将数据依次存入队列 time.sleep (1) print "%s:%s finished!"% (Time.ctime (), Self.getname ()) # Consumer threadclass Consumer_even (threading. Thread): Def __init__ (self,t_name,queue): Threading. thread.__init__ (self,name=t_name) Self.data=queue def run (self): while 1:try:val_even = Self.data.get (1,5) #get (self, block=true, timeout=none), 1 is blocking wait, 5 is timeout 5 seconds if Val_even%2==0:print "%s:%s is consuming. %d in the queue is consumed! "% (Time.ctime (), Self.getname (), Val_even) Time.sleep (2) Else:         Self.data.put (Val_even) time.sleep (2) except: #等待输入, the exception is 5 seconds print "%s:%s finished!"% (t Ime.ctime (), Self.getname ()) Breakclass consumer_odd (threading. Thread): Def __init__ (self,t_name,queue): Threading. Thread.__init__ (self, name=t_name) Self.data=queue def run (self): while 1:try:val_odd = Self.data.get (1,5) If Val_odd%2!=0:print "%s:%s is consuming. %d in the queue is consumed! "% (Time.ctime (), Self.getname (), val_odd) Time.sleep (2) else:self.        Data.put (val_odd) time.sleep (2) except:print "%s:%s finished!"% (Time.ctime (), Self.getname ()) Break#main threaddef Main (): queue = Queue () producer = producer (' Pro. ', queue) Consumer_even = Consumer_even (' Con_ Even. ', queue) consumer_odd = Consumer_odd (' con_odd. ', queue) Producer.start () Consumer_even.start () Consumer_odd.star T () Producer.join () Consumer_even.join () consumer_odd.join () print ' All tHreads terminate! ' if __name__ = = ' __main__ ': Main () 
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.