Python's Queue module detailed

Source: Internet
Author: User

Queue

Queue is a thread-safe queuing (FIFO) implementation in the Python standard library, providing a first-in-one data structure for multithreaded programming, a queue that is used to transfer information between producers and consumer threads

Basic FIFO queue

Class Queue.queue (maxsize=0)

FIFO is the first in. The queue provides a basic FIFO container, which is simple to use, and MaxSize is an integer that indicates the upper bound of the number of data that can be stored in the queue. Once the upper limit is reached, the insertion causes blocking until the data in the queue is consumed. If MaxSize is less than or equal to 0, there is no limit to the queue size.

Give me a chestnut:

1 Import Queue2 3 q = Queue.queue () 4 5 for I in range (5): 6     q.put (i) 7 8 and not Q.empty (): 9     print Q.get ()

Output:

01234

LIFO queue

Class Queue.lifoqueue (maxsize=0)

LIFO is last in first out, LIFO. Similar to the stack, the use is also very simple, maxsize usage ibid.

Give me another chestnut:

1 Import Queue2 3 q = Queue.lifoqueue () 4 5 for I in range (5): 6     q.put (i) 7 8 and not Q.empty (): 9     print Q.get ()

Output:

43210

You can see that just Queue.Quenu类 replacing theQueue.LifiQueue类

Priority queue

Class Queue.priorityqueue (maxsize=0)

Constructs a priority queue. MaxSize usage Ibid.

Import Queueimport Threadingclass Job (object):d EF __init__ (Self, Priority, description):        self.priority = priority< c1/>self.description = Descriptionprint ' Job: ', Descriptionreturndef __cmp__ (self, Other): Return CMP (self.priority, other.priority) Q = Queue.priorityqueue () q.put (Job (3, ' Level 3 job ')) Q.put (Job ("Level Job")) Q.put (Job (1, ' Level 1 J OB ')) def process_job (q): While True:        next_job = Q.get () print ' for: ', next_job.description        q.task_done () Workers = [Threading. Thread (Target=process_job, args= (Q,)),        Threading. Thread (Target=process_job, args= (Q,))        ]for W in workers:    W.setdaemon (True) W.start (    ) q.join () result job: Level 3 Jobjob:level jobjob:level 1 jobfor:level 1 jobfor:level 3 Jobfor:job:level Job

Some common methods

Task_done ()

means that one of the previous missions has been completed. Called by the consumer thread of the queue. Each get () call gets a task, and the next Task_done () call tells the queue that the task has been processed.

If the current join () is blocking, it resumes execution when all the tasks in the queue have been processed (that is, every task queued by a put () call has a corresponding task_done () call).

Join ()

Blocks the calling thread until all tasks in the queue are processed.

As long as there is data queued, the number of unfinished tasks increases. The number of unfinished tasks is reduced when the consumer thread calls Task_done () (meaning that there is a consumer getting the task and completing the task). When the number of unfinished tasks drops to 0,join () is unblocked.

Put (item[, block[, timeout])

Put the item in the queue.

    1. If the optional parameter is block true and timeout is an empty object (by default, blocking calls, no timeouts).

    2. If timeout is a positive integer, it blocks the calling process up to timeout seconds, and throws a full exception (a blocking call with a timeout) if there is no empty space available.

    3. If block is false, throw the full exception immediately if there is free space available to put the data in the queue

Its non-blocking version is put_nowait equivalent toput(item, False)

Get ([block[, timeout]])

Removes from the queue and returns a data. Block with timeout parameter same put method

Its non-blocking method is ' get_nowait () ' equivalent toget(False)

Empty ()

Returns true if the queue is empty, and vice versa returns false

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.