Movatterモバイル変換


[0]ホーム

URL:


This document is for an old version of Python that is no longer supported. You should upgrade, and read the Python documentation for the current stable release.

Navigation

17.7.queue — A synchronized queue class

Source code:Lib/queue.py


Thequeue module implements multi-producer, multi-consumer queues.It is especially useful in threaded programming when information must beexchanged safely between multiple threads. TheQueue class in thismodule implements all the required locking semantics. It depends on theavailability of thread support in Python; see thethreadingmodule.

The module implements three types of queue, which differ only in the order inwhich the entries are retrieved. In a FIFO queue, the first tasks added arethe first retrieved. In a LIFO queue, the most recently added entry isthe first retrieved (operating like a stack). With a priority queue,the entries are kept sorted (using theheapq module) and thelowest valued entry is retrieved first.

Thequeue module defines the following classes and exceptions:

classqueue.Queue(maxsize=0)

Constructor for a FIFO queue.maxsize is an integer that sets the upperboundlimit on the number of items that can be placed in the queue. Insertion willblock once this size has been reached, until queue items are consumed. Ifmaxsize is less than or equal to zero, the queue size is infinite.

classqueue.LifoQueue(maxsize=0)

Constructor for a LIFO queue.maxsize is an integer that sets the upperboundlimit on the number of items that can be placed in the queue. Insertion willblock once this size has been reached, until queue items are consumed. Ifmaxsize is less than or equal to zero, the queue size is infinite.

classqueue.PriorityQueue(maxsize=0)

Constructor for a priority queue.maxsize is an integer that sets the upperboundlimit on the number of items that can be placed in the queue. Insertion willblock once this size has been reached, until queue items are consumed. Ifmaxsize is less than or equal to zero, the queue size is infinite.

The lowest valued entries are retrieved first (the lowest valued entry is theone returned bysorted(list(entries))[0]). A typical pattern for entriesis a tuple in the form:(priority_number,data).

exceptionqueue.Empty

Exception raised when non-blockingget() (orget_nowait()) is calledon aQueue object which is empty.

exceptionqueue.Full

Exception raised when non-blockingput() (orput_nowait()) is calledon aQueue object which is full.

17.7.1. Queue Objects

Queue objects (Queue,LifoQueue, orPriorityQueue)provide the public methods described below.

Queue.qsize()

Return the approximate size of the queue. Note, qsize() > 0 doesn’tguarantee that a subsequent get() will not block, nor will qsize() < maxsizeguarantee that put() will not block.

Queue.empty()

ReturnTrue if the queue is empty,False otherwise. If empty()returnsTrue it doesn’t guarantee that a subsequent call to put()will not block. Similarly, if empty() returnsFalse it doesn’tguarantee that a subsequent call to get() will not block.

Queue.full()

ReturnTrue if the queue is full,False otherwise. If full()returnsTrue it doesn’t guarantee that a subsequent call to get()will not block. Similarly, if full() returnsFalse it doesn’tguarantee that a subsequent call to put() will not block.

Queue.put(item,block=True,timeout=None)

Putitem into the queue. If optional argsblock is true andtimeout isNone (the default), block if necessary until a free slot is available. Iftimeout is a positive number, it blocks at mosttimeout seconds and raisestheFull exception if no free slot was available within that time.Otherwise (block is false), put an item on the queue if a free slot isimmediately available, else raise theFull exception (timeout isignored in that case).

Queue.put_nowait(item)

Equivalent toput(item,False).

Queue.get(block=True,timeout=None)

Remove and return an item from the queue. If optional argsblock is true andtimeout is None (the default), block if necessary until an item is available.Iftimeout is a positive number, it blocks at mosttimeout seconds andraises theEmpty exception if no item was available within that time.Otherwise (block is false), return an item if one is immediately available,else raise theEmpty exception (timeout is ignored in that case).

Queue.get_nowait()

Equivalent toget(False).

Two methods are offered to support tracking whether enqueued tasks have beenfully processed by daemon consumer threads.

Queue.task_done()

Indicate that a formerly enqueued task is complete. Used by queue consumerthreads. For eachget() used to fetch a task, a subsequent call totask_done() tells the queue that the processing on the task is complete.

If ajoin() is currently blocking, it will resume when all items have beenprocessed (meaning that atask_done() call was received for every itemthat had beenput() into the queue).

Raises aValueError if called more times than there were items placed inthe queue.

Queue.join()

Blocks until all items in the queue have been gotten and processed.

The count of unfinished tasks goes up whenever an item is added to the queue.The count goes down whenever a consumer thread callstask_done() toindicate that the item was retrieved and all work on it is complete. When thecount of unfinished tasks drops to zero,join() unblocks.

Example of how to wait for enqueued tasks to be completed:

defworker():whileTrue:item=q.get()do_work(item)q.task_done()q=Queue()foriinrange(num_worker_threads):t=Thread(target=worker)t.daemon=Truet.start()foriteminsource():q.put(item)q.join()# block until all tasks are done

See also

Classmultiprocessing.Queue
A queue class for use in a multi-processing (rather than multi-threading)context.

collections.deque is an alternative implementation of unboundedqueues with fast atomicappend() andpopleft() operations that do not require locking.

Table Of Contents

Previous topic

17.6.sched — Event scheduler

Next topic

17.8.dummy_threading — Drop-in replacement for thethreading module

This Page

Quick search

Enter search terms or a module, class or function name.

Navigation

©Copyright 1990-2019, Python Software Foundation.
The Python Software Foundation is a non-profit corporation.Please donate.
Last updated on Jun 16, 2019.Found a bug?
Created usingSphinx 1.2.3.

[8]ページ先頭

©2009-2025 Movatter.jp