gooderp18绿色标准版
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

548 lines
34KB

  1. <!DOCTYPE html>
  2. <html lang="en" data-content_root="../">
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
  6. <meta property="og:title" content="Queues" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/library/asyncio-queue.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="Source code: Lib/asyncio/queues.py asyncio queues are designed to be similar to classes of the queue module. Although asyncio queues are not thread-safe, they are designed to be used specifically i..." />
  11. <meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
  12. <meta property="og:image:alt" content="Python documentation" />
  13. <meta name="description" content="Source code: Lib/asyncio/queues.py asyncio queues are designed to be similar to classes of the queue module. Although asyncio queues are not thread-safe, they are designed to be used specifically i..." />
  14. <meta property="og:image:width" content="200" />
  15. <meta property="og:image:height" content="200" />
  16. <meta name="theme-color" content="#3776ab" />
  17. <title>Queues &#8212; Python 3.12.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
  18. <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=80d5e7a1" />
  19. <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=bb723527" />
  20. <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=b20cc3f5" />
  21. <script src="../_static/documentation_options.js?v=2c828074"></script>
  22. <script src="../_static/doctools.js?v=888ff710"></script>
  23. <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
  24. <script src="../_static/sidebar.js"></script>
  25. <link rel="search" type="application/opensearchdescription+xml"
  26. title="Search within Python 3.12.3 documentation"
  27. href="../_static/opensearch.xml"/>
  28. <link rel="author" title="About these documents" href="../about.html" />
  29. <link rel="index" title="Index" href="../genindex.html" />
  30. <link rel="search" title="Search" href="../search.html" />
  31. <link rel="copyright" title="Copyright" href="../copyright.html" />
  32. <link rel="next" title="Exceptions" href="asyncio-exceptions.html" />
  33. <link rel="prev" title="Subprocesses" href="asyncio-subprocess.html" />
  34. <link rel="canonical" href="https://docs.python.org/3/library/asyncio-queue.html" />
  35. <style>
  36. @media only screen {
  37. table.full-width-table {
  38. width: 100%;
  39. }
  40. }
  41. </style>
  42. <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
  43. <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
  44. <script type="text/javascript" src="../_static/copybutton.js"></script>
  45. <script type="text/javascript" src="../_static/menu.js"></script>
  46. <script type="text/javascript" src="../_static/search-focus.js"></script>
  47. <script type="text/javascript" src="../_static/themetoggle.js"></script>
  48. </head>
  49. <body>
  50. <div class="mobile-nav">
  51. <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
  52. aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
  53. <nav class="nav-content" role="navigation">
  54. <label for="menuToggler" class="toggler__label">
  55. <span></span>
  56. </label>
  57. <span class="nav-items-wrapper">
  58. <a href="https://www.python.org/" class="nav-logo">
  59. <img src="../_static/py.svg" alt="Python logo"/>
  60. </a>
  61. <span class="version_switcher_placeholder"></span>
  62. <form role="search" class="search" action="../search.html" method="get">
  63. <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
  64. <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
  65. </svg>
  66. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  67. <input type="submit" value="Go"/>
  68. </form>
  69. </span>
  70. </nav>
  71. <div class="menu-wrapper">
  72. <nav class="menu" role="navigation" aria-label="main navigation">
  73. <div class="language_switcher_placeholder"></div>
  74. <label class="theme-selector-label">
  75. Theme
  76. <select class="theme-selector" oninput="activateTheme(this.value)">
  77. <option value="auto" selected>Auto</option>
  78. <option value="light">Light</option>
  79. <option value="dark">Dark</option>
  80. </select>
  81. </label>
  82. <div>
  83. <h3><a href="../contents.html">Table of Contents</a></h3>
  84. <ul>
  85. <li><a class="reference internal" href="#">Queues</a><ul>
  86. <li><a class="reference internal" href="#queue">Queue</a></li>
  87. <li><a class="reference internal" href="#priority-queue">Priority Queue</a></li>
  88. <li><a class="reference internal" href="#lifo-queue">LIFO Queue</a></li>
  89. <li><a class="reference internal" href="#exceptions">Exceptions</a></li>
  90. <li><a class="reference internal" href="#examples">Examples</a></li>
  91. </ul>
  92. </li>
  93. </ul>
  94. </div>
  95. <div>
  96. <h4>Previous topic</h4>
  97. <p class="topless"><a href="asyncio-subprocess.html"
  98. title="previous chapter">Subprocesses</a></p>
  99. </div>
  100. <div>
  101. <h4>Next topic</h4>
  102. <p class="topless"><a href="asyncio-exceptions.html"
  103. title="next chapter">Exceptions</a></p>
  104. </div>
  105. <div role="note" aria-label="source link">
  106. <h3>This Page</h3>
  107. <ul class="this-page-menu">
  108. <li><a href="../bugs.html">Report a Bug</a></li>
  109. <li>
  110. <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-queue.rst"
  111. rel="nofollow">Show Source
  112. </a>
  113. </li>
  114. </ul>
  115. </div>
  116. </nav>
  117. </div>
  118. </div>
  119. <div class="related" role="navigation" aria-label="related navigation">
  120. <h3>Navigation</h3>
  121. <ul>
  122. <li class="right" style="margin-right: 10px">
  123. <a href="../genindex.html" title="General Index"
  124. accesskey="I">index</a></li>
  125. <li class="right" >
  126. <a href="../py-modindex.html" title="Python Module Index"
  127. >modules</a> |</li>
  128. <li class="right" >
  129. <a href="asyncio-exceptions.html" title="Exceptions"
  130. accesskey="N">next</a> |</li>
  131. <li class="right" >
  132. <a href="asyncio-subprocess.html" title="Subprocesses"
  133. accesskey="P">previous</a> |</li>
  134. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  135. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  136. <li class="switchers">
  137. <div class="language_switcher_placeholder"></div>
  138. <div class="version_switcher_placeholder"></div>
  139. </li>
  140. <li>
  141. </li>
  142. <li id="cpython-language-and-version">
  143. <a href="../index.html">3.12.3 Documentation</a> &#187;
  144. </li>
  145. <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
  146. <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> &#187;</li>
  147. <li class="nav-item nav-item-3"><a href="asyncio.html" accesskey="U"><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code> — Asynchronous I/O</a> &#187;</li>
  148. <li class="nav-item nav-item-this"><a href="">Queues</a></li>
  149. <li class="right">
  150. <div class="inline-search" role="search">
  151. <form class="inline-search" action="../search.html" method="get">
  152. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  153. <input type="submit" value="Go" />
  154. </form>
  155. </div>
  156. |
  157. </li>
  158. <li class="right">
  159. <label class="theme-selector-label">
  160. Theme
  161. <select class="theme-selector" oninput="activateTheme(this.value)">
  162. <option value="auto" selected>Auto</option>
  163. <option value="light">Light</option>
  164. <option value="dark">Dark</option>
  165. </select>
  166. </label> |</li>
  167. </ul>
  168. </div>
  169. <div class="document">
  170. <div class="documentwrapper">
  171. <div class="bodywrapper">
  172. <div class="body" role="main">
  173. <section id="queues">
  174. <span id="asyncio-queues"></span><h1>Queues<a class="headerlink" href="#queues" title="Link to this heading">¶</a></h1>
  175. <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/asyncio/queues.py">Lib/asyncio/queues.py</a></p>
  176. <hr class="docutils" />
  177. <p>asyncio queues are designed to be similar to classes of the
  178. <a class="reference internal" href="queue.html#module-queue" title="queue: A synchronized queue class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">queue</span></code></a> module. Although asyncio queues are not thread-safe,
  179. they are designed to be used specifically in async/await code.</p>
  180. <p>Note that methods of asyncio queues don’t have a <em>timeout</em> parameter;
  181. use <a class="reference internal" href="asyncio-task.html#asyncio.wait_for" title="asyncio.wait_for"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.wait_for()</span></code></a> function to do queue operations with a
  182. timeout.</p>
  183. <p>See also the <a class="reference internal" href="#examples">Examples</a> section below.</p>
  184. <section id="queue">
  185. <h2>Queue<a class="headerlink" href="#queue" title="Link to this heading">¶</a></h2>
  186. <dl class="py class">
  187. <dt class="sig sig-object py" id="asyncio.Queue">
  188. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">Queue</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">maxsize</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">0</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Queue" title="Link to this definition">¶</a></dt>
  189. <dd><p>A first in, first out (FIFO) queue.</p>
  190. <p>If <em>maxsize</em> is less than or equal to zero, the queue size is
  191. infinite. If it is an integer greater than <code class="docutils literal notranslate"><span class="pre">0</span></code>, then
  192. <code class="docutils literal notranslate"><span class="pre">await</span> <span class="pre">put()</span></code> blocks when the queue reaches <em>maxsize</em>
  193. until an item is removed by <a class="reference internal" href="#asyncio.Queue.get" title="asyncio.Queue.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a>.</p>
  194. <p>Unlike the standard library threading <a class="reference internal" href="queue.html#module-queue" title="queue: A synchronized queue class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">queue</span></code></a>, the size of
  195. the queue is always known and can be returned by calling the
  196. <a class="reference internal" href="#asyncio.Queue.qsize" title="asyncio.Queue.qsize"><code class="xref py py-meth docutils literal notranslate"><span class="pre">qsize()</span></code></a> method.</p>
  197. <div class="versionchanged">
  198. <p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p>
  199. </div>
  200. <p>This class is <a class="reference internal" href="asyncio-dev.html#asyncio-multithreading"><span class="std std-ref">not thread safe</span></a>.</p>
  201. <dl class="py attribute">
  202. <dt class="sig sig-object py" id="asyncio.Queue.maxsize">
  203. <span class="sig-name descname"><span class="pre">maxsize</span></span><a class="headerlink" href="#asyncio.Queue.maxsize" title="Link to this definition">¶</a></dt>
  204. <dd><p>Number of items allowed in the queue.</p>
  205. </dd></dl>
  206. <dl class="py method">
  207. <dt class="sig sig-object py" id="asyncio.Queue.empty">
  208. <span class="sig-name descname"><span class="pre">empty</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Queue.empty" title="Link to this definition">¶</a></dt>
  209. <dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the queue is empty, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.</p>
  210. </dd></dl>
  211. <dl class="py method">
  212. <dt class="sig sig-object py" id="asyncio.Queue.full">
  213. <span class="sig-name descname"><span class="pre">full</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Queue.full" title="Link to this definition">¶</a></dt>
  214. <dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if there are <a class="reference internal" href="#asyncio.Queue.maxsize" title="asyncio.Queue.maxsize"><code class="xref py py-attr docutils literal notranslate"><span class="pre">maxsize</span></code></a> items in the queue.</p>
  215. <p>If the queue was initialized with <code class="docutils literal notranslate"><span class="pre">maxsize=0</span></code> (the default),
  216. then <a class="reference internal" href="#asyncio.Queue.full" title="asyncio.Queue.full"><code class="xref py py-meth docutils literal notranslate"><span class="pre">full()</span></code></a> never returns <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
  217. </dd></dl>
  218. <dl class="py method">
  219. <dt class="sig sig-object py" id="asyncio.Queue.get">
  220. <em class="property"><span class="pre">coroutine</span> </em><span class="sig-name descname"><span class="pre">get</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Queue.get" title="Link to this definition">¶</a></dt>
  221. <dd><p>Remove and return an item from the queue. If queue is empty,
  222. wait until an item is available.</p>
  223. </dd></dl>
  224. <dl class="py method">
  225. <dt class="sig sig-object py" id="asyncio.Queue.get_nowait">
  226. <span class="sig-name descname"><span class="pre">get_nowait</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Queue.get_nowait" title="Link to this definition">¶</a></dt>
  227. <dd><p>Return an item if one is immediately available, else raise
  228. <a class="reference internal" href="#asyncio.QueueEmpty" title="asyncio.QueueEmpty"><code class="xref py py-exc docutils literal notranslate"><span class="pre">QueueEmpty</span></code></a>.</p>
  229. </dd></dl>
  230. <dl class="py method">
  231. <dt class="sig sig-object py" id="asyncio.Queue.join">
  232. <em class="property"><span class="pre">coroutine</span> </em><span class="sig-name descname"><span class="pre">join</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Queue.join" title="Link to this definition">¶</a></dt>
  233. <dd><p>Block until all items in the queue have been received and processed.</p>
  234. <p>The count of unfinished tasks goes up whenever an item is added
  235. to the queue. The count goes down whenever a consumer coroutine calls
  236. <a class="reference internal" href="#asyncio.Queue.task_done" title="asyncio.Queue.task_done"><code class="xref py py-meth docutils literal notranslate"><span class="pre">task_done()</span></code></a> to indicate that the item was retrieved and all
  237. work on it is complete. When the count of unfinished tasks drops
  238. to zero, <a class="reference internal" href="#asyncio.Queue.join" title="asyncio.Queue.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> unblocks.</p>
  239. </dd></dl>
  240. <dl class="py method">
  241. <dt class="sig sig-object py" id="asyncio.Queue.put">
  242. <em class="property"><span class="pre">coroutine</span> </em><span class="sig-name descname"><span class="pre">put</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">item</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Queue.put" title="Link to this definition">¶</a></dt>
  243. <dd><p>Put an item into the queue. If the queue is full, wait until a
  244. free slot is available before adding the item.</p>
  245. </dd></dl>
  246. <dl class="py method">
  247. <dt class="sig sig-object py" id="asyncio.Queue.put_nowait">
  248. <span class="sig-name descname"><span class="pre">put_nowait</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">item</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Queue.put_nowait" title="Link to this definition">¶</a></dt>
  249. <dd><p>Put an item into the queue without blocking.</p>
  250. <p>If no free slot is immediately available, raise <a class="reference internal" href="#asyncio.QueueFull" title="asyncio.QueueFull"><code class="xref py py-exc docutils literal notranslate"><span class="pre">QueueFull</span></code></a>.</p>
  251. </dd></dl>
  252. <dl class="py method">
  253. <dt class="sig sig-object py" id="asyncio.Queue.qsize">
  254. <span class="sig-name descname"><span class="pre">qsize</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Queue.qsize" title="Link to this definition">¶</a></dt>
  255. <dd><p>Return the number of items in the queue.</p>
  256. </dd></dl>
  257. <dl class="py method">
  258. <dt class="sig sig-object py" id="asyncio.Queue.task_done">
  259. <span class="sig-name descname"><span class="pre">task_done</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Queue.task_done" title="Link to this definition">¶</a></dt>
  260. <dd><p>Indicate that a formerly enqueued task is complete.</p>
  261. <p>Used by queue consumers. For each <a class="reference internal" href="#asyncio.Queue.get" title="asyncio.Queue.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a> used to
  262. fetch a task, a subsequent call to <a class="reference internal" href="#asyncio.Queue.task_done" title="asyncio.Queue.task_done"><code class="xref py py-meth docutils literal notranslate"><span class="pre">task_done()</span></code></a> tells the
  263. queue that the processing on the task is complete.</p>
  264. <p>If a <a class="reference internal" href="#asyncio.Queue.join" title="asyncio.Queue.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> is currently blocking, it will resume when all
  265. items have been processed (meaning that a <a class="reference internal" href="#asyncio.Queue.task_done" title="asyncio.Queue.task_done"><code class="xref py py-meth docutils literal notranslate"><span class="pre">task_done()</span></code></a>
  266. call was received for every item that had been <a class="reference internal" href="#asyncio.Queue.put" title="asyncio.Queue.put"><code class="xref py py-meth docutils literal notranslate"><span class="pre">put()</span></code></a>
  267. into the queue).</p>
  268. <p>Raises <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if called more times than there were
  269. items placed in the queue.</p>
  270. </dd></dl>
  271. </dd></dl>
  272. </section>
  273. <section id="priority-queue">
  274. <h2>Priority Queue<a class="headerlink" href="#priority-queue" title="Link to this heading">¶</a></h2>
  275. <dl class="py class">
  276. <dt class="sig sig-object py" id="asyncio.PriorityQueue">
  277. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">PriorityQueue</span></span><a class="headerlink" href="#asyncio.PriorityQueue" title="Link to this definition">¶</a></dt>
  278. <dd><p>A variant of <a class="reference internal" href="#asyncio.Queue" title="asyncio.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a>; retrieves entries in priority order
  279. (lowest first).</p>
  280. <p>Entries are typically tuples of the form
  281. <code class="docutils literal notranslate"><span class="pre">(priority_number,</span> <span class="pre">data)</span></code>.</p>
  282. </dd></dl>
  283. </section>
  284. <section id="lifo-queue">
  285. <h2>LIFO Queue<a class="headerlink" href="#lifo-queue" title="Link to this heading">¶</a></h2>
  286. <dl class="py class">
  287. <dt class="sig sig-object py" id="asyncio.LifoQueue">
  288. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">LifoQueue</span></span><a class="headerlink" href="#asyncio.LifoQueue" title="Link to this definition">¶</a></dt>
  289. <dd><p>A variant of <a class="reference internal" href="#asyncio.Queue" title="asyncio.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a> that retrieves most recently added
  290. entries first (last in, first out).</p>
  291. </dd></dl>
  292. </section>
  293. <section id="exceptions">
  294. <h2>Exceptions<a class="headerlink" href="#exceptions" title="Link to this heading">¶</a></h2>
  295. <dl class="py exception">
  296. <dt class="sig sig-object py" id="asyncio.QueueEmpty">
  297. <em class="property"><span class="pre">exception</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">QueueEmpty</span></span><a class="headerlink" href="#asyncio.QueueEmpty" title="Link to this definition">¶</a></dt>
  298. <dd><p>This exception is raised when the <a class="reference internal" href="#asyncio.Queue.get_nowait" title="asyncio.Queue.get_nowait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_nowait()</span></code></a> method
  299. is called on an empty queue.</p>
  300. </dd></dl>
  301. <dl class="py exception">
  302. <dt class="sig sig-object py" id="asyncio.QueueFull">
  303. <em class="property"><span class="pre">exception</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">QueueFull</span></span><a class="headerlink" href="#asyncio.QueueFull" title="Link to this definition">¶</a></dt>
  304. <dd><p>Exception raised when the <a class="reference internal" href="#asyncio.Queue.put_nowait" title="asyncio.Queue.put_nowait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">put_nowait()</span></code></a> method is called
  305. on a queue that has reached its <em>maxsize</em>.</p>
  306. </dd></dl>
  307. </section>
  308. <section id="examples">
  309. <h2>Examples<a class="headerlink" href="#examples" title="Link to this heading">¶</a></h2>
  310. <p id="asyncio-example-queue-dist">Queues can be used to distribute workload between several
  311. concurrent tasks:</p>
  312. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
  313. <span class="kn">import</span> <span class="nn">random</span>
  314. <span class="kn">import</span> <span class="nn">time</span>
  315. <span class="k">async</span> <span class="k">def</span> <span class="nf">worker</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">queue</span><span class="p">):</span>
  316. <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
  317. <span class="c1"># Get a &quot;work item&quot; out of the queue.</span>
  318. <span class="n">sleep_for</span> <span class="o">=</span> <span class="k">await</span> <span class="n">queue</span><span class="o">.</span><span class="n">get</span><span class="p">()</span>
  319. <span class="c1"># Sleep for the &quot;sleep_for&quot; seconds.</span>
  320. <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="n">sleep_for</span><span class="p">)</span>
  321. <span class="c1"># Notify the queue that the &quot;work item&quot; has been processed.</span>
  322. <span class="n">queue</span><span class="o">.</span><span class="n">task_done</span><span class="p">()</span>
  323. <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">name</span><span class="si">}</span><span class="s1"> has slept for </span><span class="si">{</span><span class="n">sleep_for</span><span class="si">:</span><span class="s1">.2f</span><span class="si">}</span><span class="s1"> seconds&#39;</span><span class="p">)</span>
  324. <span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
  325. <span class="c1"># Create a queue that we will use to store our &quot;workload&quot;.</span>
  326. <span class="n">queue</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">Queue</span><span class="p">()</span>
  327. <span class="c1"># Generate random timings and put them into the queue.</span>
  328. <span class="n">total_sleep_time</span> <span class="o">=</span> <span class="mi">0</span>
  329. <span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">20</span><span class="p">):</span>
  330. <span class="n">sleep_for</span> <span class="o">=</span> <span class="n">random</span><span class="o">.</span><span class="n">uniform</span><span class="p">(</span><span class="mf">0.05</span><span class="p">,</span> <span class="mf">1.0</span><span class="p">)</span>
  331. <span class="n">total_sleep_time</span> <span class="o">+=</span> <span class="n">sleep_for</span>
  332. <span class="n">queue</span><span class="o">.</span><span class="n">put_nowait</span><span class="p">(</span><span class="n">sleep_for</span><span class="p">)</span>
  333. <span class="c1"># Create three worker tasks to process the queue concurrently.</span>
  334. <span class="n">tasks</span> <span class="o">=</span> <span class="p">[]</span>
  335. <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">):</span>
  336. <span class="n">task</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">create_task</span><span class="p">(</span><span class="n">worker</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;worker-</span><span class="si">{</span><span class="n">i</span><span class="si">}</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">queue</span><span class="p">))</span>
  337. <span class="n">tasks</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">task</span><span class="p">)</span>
  338. <span class="c1"># Wait until the queue is fully processed.</span>
  339. <span class="n">started_at</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">monotonic</span><span class="p">()</span>
  340. <span class="k">await</span> <span class="n">queue</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>
  341. <span class="n">total_slept_for</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">monotonic</span><span class="p">()</span> <span class="o">-</span> <span class="n">started_at</span>
  342. <span class="c1"># Cancel our worker tasks.</span>
  343. <span class="k">for</span> <span class="n">task</span> <span class="ow">in</span> <span class="n">tasks</span><span class="p">:</span>
  344. <span class="n">task</span><span class="o">.</span><span class="n">cancel</span><span class="p">()</span>
  345. <span class="c1"># Wait until all worker tasks are cancelled.</span>
  346. <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">gather</span><span class="p">(</span><span class="o">*</span><span class="n">tasks</span><span class="p">,</span> <span class="n">return_exceptions</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
  347. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;====&#39;</span><span class="p">)</span>
  348. <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;3 workers slept in parallel for </span><span class="si">{</span><span class="n">total_slept_for</span><span class="si">:</span><span class="s1">.2f</span><span class="si">}</span><span class="s1"> seconds&#39;</span><span class="p">)</span>
  349. <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;total expected sleep time: </span><span class="si">{</span><span class="n">total_sleep_time</span><span class="si">:</span><span class="s1">.2f</span><span class="si">}</span><span class="s1"> seconds&#39;</span><span class="p">)</span>
  350. <span class="n">asyncio</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">main</span><span class="p">())</span>
  351. </pre></div>
  352. </div>
  353. </section>
  354. </section>
  355. <div class="clearer"></div>
  356. </div>
  357. </div>
  358. </div>
  359. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  360. <div class="sphinxsidebarwrapper">
  361. <div>
  362. <h3><a href="../contents.html">Table of Contents</a></h3>
  363. <ul>
  364. <li><a class="reference internal" href="#">Queues</a><ul>
  365. <li><a class="reference internal" href="#queue">Queue</a></li>
  366. <li><a class="reference internal" href="#priority-queue">Priority Queue</a></li>
  367. <li><a class="reference internal" href="#lifo-queue">LIFO Queue</a></li>
  368. <li><a class="reference internal" href="#exceptions">Exceptions</a></li>
  369. <li><a class="reference internal" href="#examples">Examples</a></li>
  370. </ul>
  371. </li>
  372. </ul>
  373. </div>
  374. <div>
  375. <h4>Previous topic</h4>
  376. <p class="topless"><a href="asyncio-subprocess.html"
  377. title="previous chapter">Subprocesses</a></p>
  378. </div>
  379. <div>
  380. <h4>Next topic</h4>
  381. <p class="topless"><a href="asyncio-exceptions.html"
  382. title="next chapter">Exceptions</a></p>
  383. </div>
  384. <div role="note" aria-label="source link">
  385. <h3>This Page</h3>
  386. <ul class="this-page-menu">
  387. <li><a href="../bugs.html">Report a Bug</a></li>
  388. <li>
  389. <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-queue.rst"
  390. rel="nofollow">Show Source
  391. </a>
  392. </li>
  393. </ul>
  394. </div>
  395. </div>
  396. <div id="sidebarbutton" title="Collapse sidebar">
  397. <span>«</span>
  398. </div>
  399. </div>
  400. <div class="clearer"></div>
  401. </div>
  402. <div class="related" role="navigation" aria-label="related navigation">
  403. <h3>Navigation</h3>
  404. <ul>
  405. <li class="right" style="margin-right: 10px">
  406. <a href="../genindex.html" title="General Index"
  407. >index</a></li>
  408. <li class="right" >
  409. <a href="../py-modindex.html" title="Python Module Index"
  410. >modules</a> |</li>
  411. <li class="right" >
  412. <a href="asyncio-exceptions.html" title="Exceptions"
  413. >next</a> |</li>
  414. <li class="right" >
  415. <a href="asyncio-subprocess.html" title="Subprocesses"
  416. >previous</a> |</li>
  417. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  418. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  419. <li class="switchers">
  420. <div class="language_switcher_placeholder"></div>
  421. <div class="version_switcher_placeholder"></div>
  422. </li>
  423. <li>
  424. </li>
  425. <li id="cpython-language-and-version">
  426. <a href="../index.html">3.12.3 Documentation</a> &#187;
  427. </li>
  428. <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
  429. <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> &#187;</li>
  430. <li class="nav-item nav-item-3"><a href="asyncio.html" ><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code> — Asynchronous I/O</a> &#187;</li>
  431. <li class="nav-item nav-item-this"><a href="">Queues</a></li>
  432. <li class="right">
  433. <div class="inline-search" role="search">
  434. <form class="inline-search" action="../search.html" method="get">
  435. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  436. <input type="submit" value="Go" />
  437. </form>
  438. </div>
  439. |
  440. </li>
  441. <li class="right">
  442. <label class="theme-selector-label">
  443. Theme
  444. <select class="theme-selector" oninput="activateTheme(this.value)">
  445. <option value="auto" selected>Auto</option>
  446. <option value="light">Light</option>
  447. <option value="dark">Dark</option>
  448. </select>
  449. </label> |</li>
  450. </ul>
  451. </div>
  452. <div class="footer">
  453. &copy;
  454. <a href="../copyright.html">
  455. Copyright
  456. </a>
  457. 2001-2024, Python Software Foundation.
  458. <br />
  459. This page is licensed under the Python Software Foundation License Version 2.
  460. <br />
  461. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  462. <br />
  463. See <a href="/license.html">History and License</a> for more information.<br />
  464. <br />
  465. The Python Software Foundation is a non-profit corporation.
  466. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  467. <br />
  468. <br />
  469. Last updated on Apr 09, 2024 (13:47 UTC).
  470. <a href="/bugs.html">Found a bug</a>?
  471. <br />
  472. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 7.2.6.
  473. </div>
  474. </body>
  475. </html>
上海开阖软件有限公司 沪ICP备12045867号-1