Python Queue Module Detailed _python

Source: Internet
Author: User

In Python, queues are the most common form of exchange data between threads. Queue module is the module that provides the operation of queues, although it is simple and easy to use, there are still some surprises.

Create a "queue" object
Import Queue
Q = queue.queue (maxsize = 10)
The Queue.queue class is the synchronous implementation of a queue. The queue length can be unlimited or limited. The queue length can be set by the optional parameter maxsize of the queue's constructor. If the maxsize is less than 1, the queue length is infinite.

Put a value into the queue
Q.put (10)
The put () method of the calling queue object inserts a project at the end of the team. Put () has two parameters, the first item is required, the value of the inserted item, the second block is optional, and the default is
1. If the queue is currently empty and the Block-1,put () method suspends the calling thread until a data unit is empty. If the block is a 0,put method, a full exception is thrown.

Remove a value from the queue
Q.get ()
The Get () method of the calling queue object is deleted from the team header and returns an item. The optional argument is block, and the default is true. 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 a empty exception.

The Python queue module has three types of queues and constructors:
1, the Python queue module FIFO queues advanced first out. Class Queue.queue (MaxSize)
2, the LIFO is similar to the heap, that is, advanced and 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, false instead
Q.full () returns True if the queue is full, false instead
Q.full and maxsize size correspond
Q.get ([block[, timeout]]) Gets the 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 wait until the queue is empty, and then do something else

Example:
Implement a thread to continuously generate a random number into a queue (consider using the queue this module)
Implement a thread from the top of the queue to constantly remove the odd
Implement another thread to continuously remove the even number from the queue above

#!/usr/bin/env python #coding: UTF8 import random,threading,time from queue import Queue #Producer thread class Producer (t Hreading. 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 Randomnum=random.randint (1,99) print '%s:%s is producing%d to the queue! '% (Time.ctime (), Self.getname (), Rando Mnum) Self.data.put (randomnum) #将数据依次存入队列 time.sleep (1) print "%s:%s finished!"% (Time.ctime (), SELF.GETN Ame ()) #Consumer thread class 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.dat A.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 Consu Ming.
        %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: #等待输入, more than 5 seconds to report abnormal Print '%s:%s finished! '% (Time.ctime (), Self.getname ()) Break class 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.dat A.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:se Lf.data.put (val_odd) time.sleep (2) except:print "%s:%s finished!"% (Time.ctime (), Self.getname ( ) Break #Main thread Def Main (): queue = Queue () producer = producer (' Pro. ', queue) Consumer_even = Consume R_even (' Con_even. ', queue) consumer_odd = Consumer_odd (' con_odd. ', queue) Producer.start () Consumer_even.start () CO Nsumer_odd.start () 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.