Python Queue module

Apr 09, 2018 pm 05:31 PM
python queue module

This article mainly introduces the Python Queue module. Now I will share it with you. Friends who need it can refer to it

In Python, queues are the most commonly used form of exchanging data between threads. The Queue module is a module that provides queue operations. Although it is simple and easy to use, some accidents may still occur if you are not careful.

Create a "queue" object
import Queue
q = Queue.Queue(maxsize = 10)
Queue.Queue class i.e. It is a synchronous implementation of a queue. The queue length can be infinite or finite. The queue length can be set through the optional parameter maxsize of the Queue constructor. If maxsize is less than 1, it means the queue length is unlimited.

Put a value into the queue
q.put(10)
Call the put() method of the queue object to insert a value at the end of the queue project. put() has two parameters. The first item is required and is the value of the inserted item; the second block is an optional parameter and the default is
1. If the queue is currently empty and block is 1, the put() method causes the calling thread to pause until a data unit is vacated. If block is 0, the put method will throw a Full exception.

Remove a value from the queue
q.get()
Call the get() method of the queue object to delete it from the head of the queue and return an item. The optional parameter is block, which defaults to True. If the queue is empty and block is True, get() causes the calling thread to pause until an item becomes available. If the queue is empty and block is False, the queue will throw an Empty exception.

The Python Queue module has three queues and constructors:
1. The FIFO queue of the Python Queue module is first in, first out. class Queue.Queue(maxsize)
2. LIFO is similar to a heap, that is, first in, last out. class Queue.LifoQueue(maxsize)
3. Another method is that the lower the priority queue level, the first it will come out. class Queue.PriorityQueue(maxsize)

Commonly used methods in this package (q = Queue.Queue()):
q.qsize() Return The size of the queue
q.empty() If the queue is empty, return True, otherwise False
q.full() If the queue is full, return True, otherwise False
q.full corresponds to the maxsize size
q.get([block[, timeout]]) Gets the queue, timeout waiting time
q.get_nowait() is equivalent to q.get(False)
Non-blocking q.put(item) writes to the queue, timeout waiting time
q.put_nowait(item) is equivalent to q.put(item, False)
q.task_done() After completing a job, the q.task_done() function sends a Signal
q.join() actually means waiting until the queue is empty before performing other operations

Example:
Implementing a thread continuously Generate a random number into a queue (consider using the Queue module)
Implement a thread to continuously take out odd numbers from the above queue
Implement another thread to continuously take out even numbers from the above queue

#!/usr/bin/env python
#coding:utf8
import random,threading,time
from Queue import Queue
#Producer thread
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 range(10):  #随机产生10个数字 ,可以修改为任意大小
      randomnum=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 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.data.get(1,5) #get(self, block=True, timeout=None) ,1就是阻塞等待,5是超时5秒
        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:   #等待输入,超过5秒 就报异常
        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.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 thread
def 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.start()
  producer.join()
  consumer_even.join()
  consumer_odd.join()
  print 'All threads terminate!'
 
if __name__ == '__main__':
  main()
Copy after login

                     

The above is the detailed content of Python Queue module. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

See all articles