/Doc/library/queue.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 193 lines · 126 code · 67 blank · 0 comment · 0 complexity · f57e6c1116a494e755833ab2627122c1 MD5 · raw file

  1. :mod:`queue` --- A synchronized queue class
  2. ===========================================
  3. .. module:: Queue
  4. :synopsis: A synchronized queue class.
  5. .. note::
  6. The :mod:`Queue` module has been renamed to :mod:`queue` in Python 3.0. The
  7. :term:`2to3` tool will automatically adapt imports when converting your
  8. sources to 3.0.
  9. The :mod:`Queue` module implements multi-producer, multi-consumer queues.
  10. It is especially useful in threaded programming when information must be
  11. exchanged safely between multiple threads. The :class:`Queue` class in this
  12. module implements all the required locking semantics. It depends on the
  13. availability of thread support in Python; see the :mod:`threading`
  14. module.
  15. Implements three types of queue whose only difference is the order that
  16. the entries are retrieved. In a FIFO queue, the first tasks added are
  17. the first retrieved. In a LIFO queue, the most recently added entry is
  18. the first retrieved (operating like a stack). With a priority queue,
  19. the entries are kept sorted (using the :mod:`heapq` module) and the
  20. lowest valued entry is retrieved first.
  21. The :mod:`Queue` module defines the following classes and exceptions:
  22. .. class:: Queue(maxsize)
  23. Constructor for a FIFO queue. *maxsize* is an integer that sets the upperbound
  24. limit on the number of items that can be placed in the queue. Insertion will
  25. block once this size has been reached, until queue items are consumed. If
  26. *maxsize* is less than or equal to zero, the queue size is infinite.
  27. .. class:: LifoQueue(maxsize)
  28. Constructor for a LIFO queue. *maxsize* is an integer that sets the upperbound
  29. limit on the number of items that can be placed in the queue. Insertion will
  30. block once this size has been reached, until queue items are consumed. If
  31. *maxsize* is less than or equal to zero, the queue size is infinite.
  32. .. versionadded:: 2.6
  33. .. class:: PriorityQueue(maxsize)
  34. Constructor for a priority queue. *maxsize* is an integer that sets the upperbound
  35. limit on the number of items that can be placed in the queue. Insertion will
  36. block once this size has been reached, until queue items are consumed. If
  37. *maxsize* is less than or equal to zero, the queue size is infinite.
  38. The lowest valued entries are retrieved first (the lowest valued entry is the
  39. one returned by ``sorted(list(entries))[0]``). A typical pattern for entries
  40. is a tuple in the form: ``(priority_number, data)``.
  41. .. versionadded:: 2.6
  42. .. exception:: Empty
  43. Exception raised when non-blocking :meth:`get` (or :meth:`get_nowait`) is called
  44. on a :class:`Queue` object which is empty.
  45. .. exception:: Full
  46. Exception raised when non-blocking :meth:`put` (or :meth:`put_nowait`) is called
  47. on a :class:`Queue` object which is full.
  48. .. seealso::
  49. :class:`collections.deque` is an alternative implementation of unbounded
  50. queues with fast atomic :func:`append` and :func:`popleft` operations that
  51. do not require locking.
  52. .. _queueobjects:
  53. Queue Objects
  54. -------------
  55. Queue objects (:class:`Queue`, :class:`LifoQueue`, or :class:`PriorityQueue`)
  56. provide the public methods described below.
  57. .. method:: Queue.qsize()
  58. Return the approximate size of the queue. Note, qsize() > 0 doesn't
  59. guarantee that a subsequent get() will not block, nor will qsize() < maxsize
  60. guarantee that put() will not block.
  61. .. method:: Queue.empty()
  62. Return ``True`` if the queue is empty, ``False`` otherwise. If empty()
  63. returns ``True`` it doesn't guarantee that a subsequent call to put()
  64. will not block. Similarly, if empty() returns ``False`` it doesn't
  65. guarantee that a subsequent call to get() will not block.
  66. .. method:: Queue.full()
  67. Return ``True`` if the queue is full, ``False`` otherwise. If full()
  68. returns ``True`` it doesn't guarantee that a subsequent call to get()
  69. will not block. Similarly, if full() returns ``False`` it doesn't
  70. guarantee that a subsequent call to put() will not block.
  71. .. method:: Queue.put(item[, block[, timeout]])
  72. Put *item* into the queue. If optional args *block* is true and *timeout* is
  73. None (the default), block if necessary until a free slot is available. If
  74. *timeout* is a positive number, it blocks at most *timeout* seconds and raises
  75. the :exc:`Full` exception if no free slot was available within that time.
  76. Otherwise (*block* is false), put an item on the queue if a free slot is
  77. immediately available, else raise the :exc:`Full` exception (*timeout* is
  78. ignored in that case).
  79. .. versionadded:: 2.3
  80. The *timeout* parameter.
  81. .. method:: Queue.put_nowait(item)
  82. Equivalent to ``put(item, False)``.
  83. .. method:: Queue.get([block[, timeout]])
  84. Remove and return an item from the queue. If optional args *block* is true and
  85. *timeout* is None (the default), block if necessary until an item is available.
  86. If *timeout* is a positive number, it blocks at most *timeout* seconds and
  87. raises the :exc:`Empty` exception if no item was available within that time.
  88. Otherwise (*block* is false), return an item if one is immediately available,
  89. else raise the :exc:`Empty` exception (*timeout* is ignored in that case).
  90. .. versionadded:: 2.3
  91. The *timeout* parameter.
  92. .. method:: Queue.get_nowait()
  93. Equivalent to ``get(False)``.
  94. Two methods are offered to support tracking whether enqueued tasks have been
  95. fully processed by daemon consumer threads.
  96. .. method:: Queue.task_done()
  97. Indicate that a formerly enqueued task is complete. Used by queue consumer
  98. threads. For each :meth:`get` used to fetch a task, a subsequent call to
  99. :meth:`task_done` tells the queue that the processing on the task is complete.
  100. If a :meth:`join` is currently blocking, it will resume when all items have been
  101. processed (meaning that a :meth:`task_done` call was received for every item
  102. that had been :meth:`put` into the queue).
  103. Raises a :exc:`ValueError` if called more times than there were items placed in
  104. the queue.
  105. .. versionadded:: 2.5
  106. .. method:: Queue.join()
  107. Blocks until all items in the queue have been gotten and processed.
  108. The count of unfinished tasks goes up whenever an item is added to the queue.
  109. The count goes down whenever a consumer thread calls :meth:`task_done` to
  110. indicate that the item was retrieved and all work on it is complete. When the
  111. count of unfinished tasks drops to zero, :meth:`join` unblocks.
  112. .. versionadded:: 2.5
  113. Example of how to wait for enqueued tasks to be completed::
  114. def worker():
  115. while True:
  116. item = q.get()
  117. do_work(item)
  118. q.task_done()
  119. q = Queue()
  120. for i in range(num_worker_threads):
  121. t = Thread(target=worker)
  122. t.setDaemon(True)
  123. t.start()
  124. for item in source():
  125. q.put(item)
  126. q.join() # block until all tasks are done