search
HomeBackend DevelopmentPython TutorialDetailed explanation and example code of python queue

队列特性:先进先出(FIFO)——先进队列的元素先出队列。来源于我们生活中的队列(先排队的先办完事)。

Queue模块最常与threading模块一起构成生产-消费者模型,提供了一个适用于多线程编程的先进先出的数据结构,即队列。

该模块源码中包含5个类:

其中,Empty和Full是两个异常类,当队列的Queue.get(block=0)或者调用get_nowait()时,如果队列为空,则抛EmptyException异常。

   同理,当队列的Queue.put(block=0)或者调用put_nowait()时,如果队列为达到maxsize,则抛FullException异常。

其他三个类:

Queue类:典型的队列模型,FIFO先入先出。  class Queue.Queue(maxsize)     maxsize为队列长度,指明了队列中能存放的数据个数的上限。一旦达到上限,插入会导致阻                                                                                                                塞,

直到队列中的数据被消费掉。如果maxsize小于或者等于0,队列大小没有限制。

LifoQueue类:继承自Queue,类似于堆栈,先入后出。  class Queue.LifoQueue(maxsize)

PriorityQueue类:继承自Queue,优先级队列,级别越低越先出来。  class Queue.PriorityQueue(maxsize)

所以,只要搞定Queue类,就基本搞定Queue模块。

Queue类中常用的方法:

Queue.qsize()            返回队列的大小
Queue.empty()          如果队列为空,返回True,反之False
Queue.full()           如果队列满了,返回True,反之False
Queue.full              与 maxsize 大小对应

Queue.get([block[, timeout]])    获取队列,timeout等待时间 ,调用队列对象的get()方法从队头删除并返回一个项目。可选参数为block,默认为True。如果队列为空且block为True,get()就使调用线程暂停,直至有项目可用。如果队列为空且block为False,队列将引发Empty异常。

Queue.get_nowait()    相当于Queue.get(False)

Queue.put(item)

  写入队列,timeout等待时间 ,调用队列对象的put()方法在队尾插入一个项目。put()有两个参数,第一个item为必需的,为插入项目的值;第   二个block为可选参数,默认为1。如果队列当前为空且block为1,put()方法就使调用线程暂停,直到空出一个数据单元。如果block为0,put方法将引发Full异常。                                            

Queue.put_nowait(item) 相当Queue.put(item, False)

Queue.task_done()

  在完成一项工作之后,Queue.task_done()函数向任务已经完成的队列发送一个信号

Queue.join()

 实际上意味着等到队列为空,再执行别的操作

一个小的练习实例:

#coding:utf-8
import random, threading, time
import Queue
'''
实现了一个生产线程,用于往队列中添加随机数10个,
实现了一个消费线程,分别消耗奇数随机数和偶数随机数
'''

class 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 xrange(10):
      random_num = random.randint(1,99)
      print "%s : %s 生产了一个随机数\033[31;0m %d \033[0m放入队列中" % (time.ctime(),self.getName(),random_num)
      self.data.put(random_num)
      time.sleep(1)
    print "生产线程完成!!"


class consumer(threading.Thread):
  def __init__(self,t_name,queue):
    threading.Thread.__init__(self,name=t_name)
    self.data = queue
  def run(self):
    while True:
      try:
        tmp_num = self.data.get(1,5) #定义超时时间5秒
        if tmp_num%2 == 0:
          print "%s : %s 消耗了一个队列中的偶数随机数\033[31;0m %d \033[0m" % (time.ctime(),self.getName(),tmp_num)
          time.sleep(2)
        else:
          print "%s : %s 消耗了一个队列中的奇数随机数\033[31;0m %d \033[0m" % (time.ctime(), self.getName(), tmp_num)
          time.sleep(2)
      except:
        print "消费线程完成!!" #一旦到达超时时间5秒,会抛异常,break退出循环
        break


def main():
  queue = Queue.Queue(0)
  pro = producer('Pro', queue)
  con = consumer('Con', queue)
  pro.start()
  con.start()
  pro.join()
  con.join()
  print 'All threads complete!!!'

if __name__ == '__main__':
  main()

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.