Python ----- Queue module, pythonqueue

Source: Internet
Author: User

Python ----- Queue module, pythonqueue

The Queue module most often forms a production-consumer model together with the threading module, providing a first-in-first-out data structure suitable for multi-thread programming, that is, a Queue.

 

The module source code contains five classes:

Empty and Full are two exception classes. When Queue. get (block = 0) or get_nowait () is called, if the Queue is Empty, an EmptyException is thrown.

Similarly, when the Queue. put (block = 0) or put_nowait () is called, if the Queue reaches maxsize, A FullException exception is thrown.

The other three categories:

Queue class: a typical Queue model. The first-in-first-out mode is FIFO. Class Queue. Queue (maxsize) maxsize indicates the Queue length and specifies the maximum number of data in the Queue. Once the upper limit is reached, insertion will cause congestion until data in the queue is consumed. If maxsize is smaller than or equal to 0, there is no limit on the queue size.

LifoQueue class: inherits from the Queue, similar to a stack. It is first input and then output. Class Queue. LifoQueue (maxsize)

PriorityQueue class: inherited from Queue, priority Queue. The lower the level, the more advanced. Class Queue. PriorityQueue (maxsize)

Therefore, as long as the Queue class is completed, the Queue module is basically completed.

 

Common methods in the Queue class:

Queue. qsize () returns the size of the Queue
Queue. empty () if the Queue is empty, True is returned. Otherwise, False is returned.
Queue. full () if the Queue is full, True is returned. Otherwise, False is returned.
Queue. full corresponds to maxsize


Queue. get ([block [, timeout]) gets the Queue and timeout wait time. 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.

 

Queue. get_nowait () is equivalent to Queue. get (False)


Queue. put (item) writes to the Queue, timeout wait time, and calls 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.

Queue. put_nowait (item) is equivalent to Queue. put (item, False)
After Queue. task_done () completes a job, the Queue. task_done () function sends a signal to the completed Queue of the job.
Queue. join () actually means that when the Queue is empty, other operations will be performed.

 

A small exercise example:

 

1 # coding: UTF-8 2 import random, threading, time 3 import Queue 4''' 5 implements a production thread used to add 10 random numbers to the Queue, 6. A consumption thread is implemented, which consumes seven '''8 9 class producer (threading. thread): 10 def _ init _ (self, t_name, queue): 11 threading. thread. _ init _ (self, name = t_name) 12 self. data = queue13 def run (self): 14 for I in xrange (10): 15 random_num = random. randint () 16 print "% s: % s produced a random number \ 033 [31; 0 m % d \ 033 [0 m put into the queue" % (Time. ctime (), self. getName (), random_num) 17 self. data. put (random_num) 18 time. sleep (1) 19 print "the production thread is finished !! "20 21 22 class consumer (threading. thread): 23 def _ init _ (self, t_name, queue): 24 threading. thread. _ init _ (self, name = t_name) 25 self. data = queue26 def run (self): 27 while True: 28 try: 29 tmp_num = self. data. get () # defines the time-out period of 30 seconds if tmp_num % 2 = print "% s: % s consumes an even random number in a queue \ 033 [31; 0 m % d \ 033 [0 m "% (time. ctime (), self. getName (), tmp_num) 32 time. sleep (2) 33 else: 34 print "% s: % s consumes an odd random number in a queue \ 033 [31; 0 m % d \ 033 [0 m "% (time. ctime (), self. getName (), tmp_num) 35 time. sleep (2) 36 bytes T: 37 print "Consumption thread completed !! "# Once the timeout time reaches 5 seconds, an exception is thrown. The break exits the loop 38 break39 40 41 def main (): 42 queue = Queue. queue (0) 43 pro = producer ('pro', queue) 44 con = consumer ('Con ', queue) 45 Pro. start () 46 con. start () 47 pro. join () 48 con. join () 49 print 'all threads complete !!! '50 51 if _ name _ = '_ main _': 52 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.