Python Queue module details and examples, pythonqueue

Source: Internet
Author: User

Python Queue module details and examples, pythonqueue

Python Queue Module

In Python, a queue is the most common form of data exchange between threads. The Queue module provides Queue operations. Although it is easy to use, some exceptions may occur if you are not careful.

Create a "queue" Object

import Queueq = Queue.Queue(maxsize = 10)

The Queue. Queue class is the synchronization implementation of a Queue. The queue length can be unlimited or limited. You can set the Queue length through the optional parameter maxsize of the Queue constructor. If maxsize is smaller than 1, the queue length is infinite.

Put a value into the queue

q.put(10)

Call the put () method of the queue object to insert a project at the end of the team. Put () has two parameters. The first item is required and is the value of the inserted project. The second block is an optional parameter. The default value is 1. If the queue is empty and the block is 1, The put () method suspends the calling thread until a data unit is empty. If the block is 0, the put method will cause a Full exception.

Extract A value from the queue

q.get()

Call the get () method of the queue object to delete the queue header and return a project. The optional parameter is block. The default value is True. If the queue is empty and the block is True, get () will suspend the calling thread until a project is available. If the queue is Empty and the block is False, the queue will cause an Empty exception.

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 () returns True if the queue is empty, and Falseq if not. full () if the queue is full, True is returned, and Falseq is returned. full corresponds to maxsize. get ([block [, timeout]) get the queue, timeout wait time q. get_nowait () is equivalent to q. get (False) non-blocking q. put (item) writes to the queue, timeout wait time q. put_nowait (item) is equivalent to q. put (item, False) q. task_done () after completing a job, q. the task_done () function sends a signal q to the completed queue of the task. join () actually means that when the queue is empty, other operations will be performed.

Example:

Implement a thread to continuously generate a random number into a Queue (the Queue module is considered)

Implement a thread to constantly retrieve odd numbers from the above queue

Implement another thread to constantly retrieve even numbers from the above queue

#! /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): # generate 10 random numbers, which can be changed to any size randomnum = random. randint (1, 99) print "% s: % s is producing % d to the queue! "% (Time. ctime (), self. getName (), randomnum) self. data. put (randomnum) # store data in the queue time in sequence. 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 () # get (self, block = True, timeout = None), 1 is blocking wait, 5 is timeout for 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) failed T: # Wait for the input. If the input exceeds 5 seconds, an exception is reported. print "% s: % s finished! "% (Time. 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) failed T: 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.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.