gooderp18绿色标准版
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1482 lines
135KB

  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="threading — Thread-based parallelism" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/library/threading.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="Source code: Lib/threading.py This module constructs higher-level threading interfaces on top of the lower level_thread module. CPython implementation detail: In CPython, due to the Global Interpre..." />
  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/threading.py This module constructs higher-level threading interfaces on top of the lower level_thread module. CPython implementation detail: In CPython, due to the Global Interpre..." />
  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>threading — Thread-based parallelism &#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="multiprocessing — Process-based parallelism" href="multiprocessing.html" />
  33. <link rel="prev" title="Concurrent Execution" href="concurrency.html" />
  34. <link rel="canonical" href="https://docs.python.org/3/library/threading.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="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code> — Thread-based parallelism</a><ul>
  86. <li><a class="reference internal" href="#thread-local-data">Thread-Local Data</a></li>
  87. <li><a class="reference internal" href="#thread-objects">Thread Objects</a></li>
  88. <li><a class="reference internal" href="#lock-objects">Lock Objects</a></li>
  89. <li><a class="reference internal" href="#rlock-objects">RLock Objects</a></li>
  90. <li><a class="reference internal" href="#condition-objects">Condition Objects</a></li>
  91. <li><a class="reference internal" href="#semaphore-objects">Semaphore Objects</a><ul>
  92. <li><a class="reference internal" href="#semaphore-example"><code class="xref py py-class docutils literal notranslate"><span class="pre">Semaphore</span></code> Example</a></li>
  93. </ul>
  94. </li>
  95. <li><a class="reference internal" href="#event-objects">Event Objects</a></li>
  96. <li><a class="reference internal" href="#timer-objects">Timer Objects</a></li>
  97. <li><a class="reference internal" href="#barrier-objects">Barrier Objects</a></li>
  98. <li><a class="reference internal" href="#using-locks-conditions-and-semaphores-in-the-with-statement">Using locks, conditions, and semaphores in the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> statement</a></li>
  99. </ul>
  100. </li>
  101. </ul>
  102. </div>
  103. <div>
  104. <h4>Previous topic</h4>
  105. <p class="topless"><a href="concurrency.html"
  106. title="previous chapter">Concurrent Execution</a></p>
  107. </div>
  108. <div>
  109. <h4>Next topic</h4>
  110. <p class="topless"><a href="multiprocessing.html"
  111. title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code> — Process-based parallelism</a></p>
  112. </div>
  113. <div role="note" aria-label="source link">
  114. <h3>This Page</h3>
  115. <ul class="this-page-menu">
  116. <li><a href="../bugs.html">Report a Bug</a></li>
  117. <li>
  118. <a href="https://github.com/python/cpython/blob/main/Doc/library/threading.rst"
  119. rel="nofollow">Show Source
  120. </a>
  121. </li>
  122. </ul>
  123. </div>
  124. </nav>
  125. </div>
  126. </div>
  127. <div class="related" role="navigation" aria-label="related navigation">
  128. <h3>Navigation</h3>
  129. <ul>
  130. <li class="right" style="margin-right: 10px">
  131. <a href="../genindex.html" title="General Index"
  132. accesskey="I">index</a></li>
  133. <li class="right" >
  134. <a href="../py-modindex.html" title="Python Module Index"
  135. >modules</a> |</li>
  136. <li class="right" >
  137. <a href="multiprocessing.html" title="multiprocessing — Process-based parallelism"
  138. accesskey="N">next</a> |</li>
  139. <li class="right" >
  140. <a href="concurrency.html" title="Concurrent Execution"
  141. accesskey="P">previous</a> |</li>
  142. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  143. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  144. <li class="switchers">
  145. <div class="language_switcher_placeholder"></div>
  146. <div class="version_switcher_placeholder"></div>
  147. </li>
  148. <li>
  149. </li>
  150. <li id="cpython-language-and-version">
  151. <a href="../index.html">3.12.3 Documentation</a> &#187;
  152. </li>
  153. <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
  154. <li class="nav-item nav-item-2"><a href="concurrency.html" accesskey="U">Concurrent Execution</a> &#187;</li>
  155. <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code> — Thread-based parallelism</a></li>
  156. <li class="right">
  157. <div class="inline-search" role="search">
  158. <form class="inline-search" action="../search.html" method="get">
  159. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  160. <input type="submit" value="Go" />
  161. </form>
  162. </div>
  163. |
  164. </li>
  165. <li class="right">
  166. <label class="theme-selector-label">
  167. Theme
  168. <select class="theme-selector" oninput="activateTheme(this.value)">
  169. <option value="auto" selected>Auto</option>
  170. <option value="light">Light</option>
  171. <option value="dark">Dark</option>
  172. </select>
  173. </label> |</li>
  174. </ul>
  175. </div>
  176. <div class="document">
  177. <div class="documentwrapper">
  178. <div class="bodywrapper">
  179. <div class="body" role="main">
  180. <section id="module-threading">
  181. <span id="threading-thread-based-parallelism"></span><h1><a class="reference internal" href="#module-threading" title="threading: Thread-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> — Thread-based parallelism<a class="headerlink" href="#module-threading" title="Link to this heading">¶</a></h1>
  182. <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/threading.py">Lib/threading.py</a></p>
  183. <hr class="docutils" />
  184. <p>This module constructs higher-level threading interfaces on top of the lower
  185. level <a class="reference internal" href="_thread.html#module-_thread" title="_thread: Low-level threading API."><code class="xref py py-mod docutils literal notranslate"><span class="pre">_thread</span></code></a> module.</p>
  186. <div class="versionchanged">
  187. <p><span class="versionmodified changed">Changed in version 3.7: </span>This module used to be optional, it is now always available.</p>
  188. </div>
  189. <div class="admonition seealso">
  190. <p class="admonition-title">See also</p>
  191. <p><a class="reference internal" href="concurrent.futures.html#concurrent.futures.ThreadPoolExecutor" title="concurrent.futures.ThreadPoolExecutor"><code class="xref py py-class docutils literal notranslate"><span class="pre">concurrent.futures.ThreadPoolExecutor</span></code></a> offers a higher level interface
  192. to push tasks to a background thread without blocking execution of the
  193. calling thread, while still being able to retrieve their results when needed.</p>
  194. <p><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> provides a thread-safe interface for exchanging data between
  195. running threads.</p>
  196. <p><a class="reference internal" href="asyncio.html#module-asyncio" title="asyncio: Asynchronous I/O."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code></a> offers an alternative approach to achieving task level
  197. concurrency without requiring the use of multiple operating system threads.</p>
  198. </div>
  199. <div class="admonition note">
  200. <p class="admonition-title">Note</p>
  201. <p>In the Python 2.x series, this module contained <code class="docutils literal notranslate"><span class="pre">camelCase</span></code> names
  202. for some methods and functions. These are deprecated as of Python 3.10,
  203. but they are still supported for compatibility with Python 2.5 and lower.</p>
  204. </div>
  205. <div class="impl-detail compound">
  206. <p><strong>CPython implementation detail:</strong> In CPython, due to the <a class="reference internal" href="../glossary.html#term-global-interpreter-lock"><span class="xref std std-term">Global Interpreter Lock</span></a>, only one thread
  207. can execute Python code at once (even though certain performance-oriented
  208. libraries might overcome this limitation).
  209. If you want your application to make better use of the computational
  210. resources of multi-core machines, you are advised to use
  211. <a class="reference internal" href="multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> or <a class="reference internal" href="concurrent.futures.html#concurrent.futures.ProcessPoolExecutor" title="concurrent.futures.ProcessPoolExecutor"><code class="xref py py-class docutils literal notranslate"><span class="pre">concurrent.futures.ProcessPoolExecutor</span></code></a>.
  212. However, threading is still an appropriate model if you want to run
  213. multiple I/O-bound tasks simultaneously.</p>
  214. </div>
  215. <div class="availability docutils container">
  216. <p><a class="reference internal" href="intro.html#availability"><span class="std std-ref">Availability</span></a>: not Emscripten, not WASI.</p>
  217. <p>This module does not work or is not available on WebAssembly platforms
  218. <code class="docutils literal notranslate"><span class="pre">wasm32-emscripten</span></code> and <code class="docutils literal notranslate"><span class="pre">wasm32-wasi</span></code>. See
  219. <a class="reference internal" href="intro.html#wasm-availability"><span class="std std-ref">WebAssembly platforms</span></a> for more information.</p>
  220. </div>
  221. <p>This module defines the following functions:</p>
  222. <dl class="py function">
  223. <dt class="sig sig-object py" id="threading.active_count">
  224. <span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">active_count</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.active_count" title="Link to this definition">¶</a></dt>
  225. <dd><p>Return the number of <a class="reference internal" href="#threading.Thread" title="threading.Thread"><code class="xref py py-class docutils literal notranslate"><span class="pre">Thread</span></code></a> objects currently alive. The returned
  226. count is equal to the length of the list returned by <a class="reference internal" href="#threading.enumerate" title="threading.enumerate"><code class="xref py py-func docutils literal notranslate"><span class="pre">enumerate()</span></code></a>.</p>
  227. <p>The function <code class="docutils literal notranslate"><span class="pre">activeCount</span></code> is a deprecated alias for this function.</p>
  228. </dd></dl>
  229. <dl class="py function">
  230. <dt class="sig sig-object py" id="threading.current_thread">
  231. <span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">current_thread</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.current_thread" title="Link to this definition">¶</a></dt>
  232. <dd><p>Return the current <a class="reference internal" href="#threading.Thread" title="threading.Thread"><code class="xref py py-class docutils literal notranslate"><span class="pre">Thread</span></code></a> object, corresponding to the caller’s thread
  233. of control. If the caller’s thread of control was not created through the
  234. <a class="reference internal" href="#module-threading" title="threading: Thread-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module, a dummy thread object with limited functionality is
  235. returned.</p>
  236. <p>The function <code class="docutils literal notranslate"><span class="pre">currentThread</span></code> is a deprecated alias for this function.</p>
  237. </dd></dl>
  238. <dl class="py function">
  239. <dt class="sig sig-object py" id="threading.excepthook">
  240. <span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">excepthook</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">args</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">/</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#threading.excepthook" title="Link to this definition">¶</a></dt>
  241. <dd><p>Handle uncaught exception raised by <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">Thread.run()</span></code></a>.</p>
  242. <p>The <em>args</em> argument has the following attributes:</p>
  243. <ul class="simple">
  244. <li><p><em>exc_type</em>: Exception type.</p></li>
  245. <li><p><em>exc_value</em>: Exception value, can be <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p></li>
  246. <li><p><em>exc_traceback</em>: Exception traceback, can be <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p></li>
  247. <li><p><em>thread</em>: Thread which raised the exception, can be <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p></li>
  248. </ul>
  249. <p>If <em>exc_type</em> is <a class="reference internal" href="exceptions.html#SystemExit" title="SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a>, the exception is silently ignored.
  250. Otherwise, the exception is printed out on <a class="reference internal" href="sys.html#sys.stderr" title="sys.stderr"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stderr</span></code></a>.</p>
  251. <p>If this function raises an exception, <a class="reference internal" href="sys.html#sys.excepthook" title="sys.excepthook"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.excepthook()</span></code></a> is called to
  252. handle it.</p>
  253. <p><a class="reference internal" href="#threading.excepthook" title="threading.excepthook"><code class="xref py py-func docutils literal notranslate"><span class="pre">threading.excepthook()</span></code></a> can be overridden to control how uncaught
  254. exceptions raised by <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">Thread.run()</span></code></a> are handled.</p>
  255. <p>Storing <em>exc_value</em> using a custom hook can create a reference cycle. It
  256. should be cleared explicitly to break the reference cycle when the
  257. exception is no longer needed.</p>
  258. <p>Storing <em>thread</em> using a custom hook can resurrect it if it is set to an
  259. object which is being finalized. Avoid storing <em>thread</em> after the custom
  260. hook completes to avoid resurrecting objects.</p>
  261. <div class="admonition seealso">
  262. <p class="admonition-title">See also</p>
  263. <p><a class="reference internal" href="sys.html#sys.excepthook" title="sys.excepthook"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.excepthook()</span></code></a> handles uncaught exceptions.</p>
  264. </div>
  265. <div class="versionadded">
  266. <p><span class="versionmodified added">New in version 3.8.</span></p>
  267. </div>
  268. </dd></dl>
  269. <dl class="py data">
  270. <dt class="sig sig-object py" id="threading.__excepthook__">
  271. <span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">__excepthook__</span></span><a class="headerlink" href="#threading.__excepthook__" title="Link to this definition">¶</a></dt>
  272. <dd><p>Holds the original value of <a class="reference internal" href="#threading.excepthook" title="threading.excepthook"><code class="xref py py-func docutils literal notranslate"><span class="pre">threading.excepthook()</span></code></a>. It is saved so that the
  273. original value can be restored in case they happen to get replaced with
  274. broken or alternative objects.</p>
  275. <div class="versionadded">
  276. <p><span class="versionmodified added">New in version 3.10.</span></p>
  277. </div>
  278. </dd></dl>
  279. <dl class="py function">
  280. <dt class="sig sig-object py" id="threading.get_ident">
  281. <span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">get_ident</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.get_ident" title="Link to this definition">¶</a></dt>
  282. <dd><p>Return the ‘thread identifier’ of the current thread. This is a nonzero
  283. integer. Its value has no direct meaning; it is intended as a magic cookie
  284. to be used e.g. to index a dictionary of thread-specific data. Thread
  285. identifiers may be recycled when a thread exits and another thread is
  286. created.</p>
  287. <div class="versionadded">
  288. <p><span class="versionmodified added">New in version 3.3.</span></p>
  289. </div>
  290. </dd></dl>
  291. <dl class="py function">
  292. <dt class="sig sig-object py" id="threading.get_native_id">
  293. <span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">get_native_id</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.get_native_id" title="Link to this definition">¶</a></dt>
  294. <dd><p>Return the native integral Thread ID of the current thread assigned by the kernel.
  295. This is a non-negative integer.
  296. Its value may be used to uniquely identify this particular thread system-wide
  297. (until the thread terminates, after which the value may be recycled by the OS).</p>
  298. <div class="availability docutils container">
  299. <p><a class="reference internal" href="intro.html#availability"><span class="std std-ref">Availability</span></a>: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX, DragonFlyBSD.</p>
  300. </div>
  301. <div class="versionadded">
  302. <p><span class="versionmodified added">New in version 3.8.</span></p>
  303. </div>
  304. </dd></dl>
  305. <dl class="py function">
  306. <dt class="sig sig-object py" id="threading.enumerate">
  307. <span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">enumerate</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.enumerate" title="Link to this definition">¶</a></dt>
  308. <dd><p>Return a list of all <a class="reference internal" href="#threading.Thread" title="threading.Thread"><code class="xref py py-class docutils literal notranslate"><span class="pre">Thread</span></code></a> objects currently active. The list
  309. includes daemonic threads and dummy thread objects created by
  310. <a class="reference internal" href="#threading.current_thread" title="threading.current_thread"><code class="xref py py-func docutils literal notranslate"><span class="pre">current_thread()</span></code></a>. It excludes terminated threads and threads
  311. that have not yet been started. However, the main thread is always part
  312. of the result, even when terminated.</p>
  313. </dd></dl>
  314. <dl class="py function">
  315. <dt class="sig sig-object py" id="threading.main_thread">
  316. <span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">main_thread</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.main_thread" title="Link to this definition">¶</a></dt>
  317. <dd><p>Return the main <a class="reference internal" href="#threading.Thread" title="threading.Thread"><code class="xref py py-class docutils literal notranslate"><span class="pre">Thread</span></code></a> object. In normal conditions, the
  318. main thread is the thread from which the Python interpreter was
  319. started.</p>
  320. <div class="versionadded">
  321. <p><span class="versionmodified added">New in version 3.4.</span></p>
  322. </div>
  323. </dd></dl>
  324. <dl class="py function">
  325. <dt class="sig sig-object py" id="threading.settrace">
  326. <span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">settrace</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">func</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#threading.settrace" title="Link to this definition">¶</a></dt>
  327. <dd><p id="index-0">Set a trace function for all threads started from the <a class="reference internal" href="#module-threading" title="threading: Thread-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module.
  328. The <em>func</em> will be passed to <a class="reference internal" href="sys.html#sys.settrace" title="sys.settrace"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.settrace()</span></code></a> for each thread, before its
  329. <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method is called.</p>
  330. </dd></dl>
  331. <dl class="py function">
  332. <dt class="sig sig-object py" id="threading.settrace_all_threads">
  333. <span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">settrace_all_threads</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">func</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#threading.settrace_all_threads" title="Link to this definition">¶</a></dt>
  334. <dd><p>Set a trace function for all threads started from the <a class="reference internal" href="#module-threading" title="threading: Thread-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module
  335. and all Python threads that are currently executing.</p>
  336. <p>The <em>func</em> will be passed to <a class="reference internal" href="sys.html#sys.settrace" title="sys.settrace"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.settrace()</span></code></a> for each thread, before its
  337. <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method is called.</p>
  338. <div class="versionadded">
  339. <p><span class="versionmodified added">New in version 3.12.</span></p>
  340. </div>
  341. </dd></dl>
  342. <dl class="py function">
  343. <dt class="sig sig-object py" id="threading.gettrace">
  344. <span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">gettrace</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.gettrace" title="Link to this definition">¶</a></dt>
  345. <dd><p id="index-1">Get the trace function as set by <a class="reference internal" href="#threading.settrace" title="threading.settrace"><code class="xref py py-func docutils literal notranslate"><span class="pre">settrace()</span></code></a>.</p>
  346. <div class="versionadded">
  347. <p><span class="versionmodified added">New in version 3.10.</span></p>
  348. </div>
  349. </dd></dl>
  350. <dl class="py function">
  351. <dt class="sig sig-object py" id="threading.setprofile">
  352. <span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">setprofile</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">func</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#threading.setprofile" title="Link to this definition">¶</a></dt>
  353. <dd><p id="index-2">Set a profile function for all threads started from the <a class="reference internal" href="#module-threading" title="threading: Thread-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module.
  354. The <em>func</em> will be passed to <a class="reference internal" href="sys.html#sys.setprofile" title="sys.setprofile"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.setprofile()</span></code></a> for each thread, before its
  355. <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method is called.</p>
  356. </dd></dl>
  357. <dl class="py function">
  358. <dt class="sig sig-object py" id="threading.setprofile_all_threads">
  359. <span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">setprofile_all_threads</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">func</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#threading.setprofile_all_threads" title="Link to this definition">¶</a></dt>
  360. <dd><p>Set a profile function for all threads started from the <a class="reference internal" href="#module-threading" title="threading: Thread-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module
  361. and all Python threads that are currently executing.</p>
  362. <p>The <em>func</em> will be passed to <a class="reference internal" href="sys.html#sys.setprofile" title="sys.setprofile"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.setprofile()</span></code></a> for each thread, before its
  363. <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method is called.</p>
  364. <div class="versionadded">
  365. <p><span class="versionmodified added">New in version 3.12.</span></p>
  366. </div>
  367. </dd></dl>
  368. <dl class="py function">
  369. <dt class="sig sig-object py" id="threading.getprofile">
  370. <span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">getprofile</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.getprofile" title="Link to this definition">¶</a></dt>
  371. <dd><p id="index-3">Get the profiler function as set by <a class="reference internal" href="#threading.setprofile" title="threading.setprofile"><code class="xref py py-func docutils literal notranslate"><span class="pre">setprofile()</span></code></a>.</p>
  372. <div class="versionadded">
  373. <p><span class="versionmodified added">New in version 3.10.</span></p>
  374. </div>
  375. </dd></dl>
  376. <dl class="py function">
  377. <dt class="sig sig-object py" id="threading.stack_size">
  378. <span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">stack_size</span></span><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param"><span class="n"><span class="pre">size</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.stack_size" title="Link to this definition">¶</a></dt>
  379. <dd><p>Return the thread stack size used when creating new threads. The optional
  380. <em>size</em> argument specifies the stack size to be used for subsequently created
  381. threads, and must be 0 (use platform or configured default) or a positive
  382. integer value of at least 32,768 (32 KiB). If <em>size</em> is not specified,
  383. 0 is used. If changing the thread stack size is
  384. unsupported, a <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised. If the specified stack size is
  385. invalid, a <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> is raised and the stack size is unmodified. 32 KiB
  386. is currently the minimum supported stack size value to guarantee sufficient
  387. stack space for the interpreter itself. Note that some platforms may have
  388. particular restrictions on values for the stack size, such as requiring a
  389. minimum stack size &gt; 32 KiB or requiring allocation in multiples of the system
  390. memory page size - platform documentation should be referred to for more
  391. information (4 KiB pages are common; using multiples of 4096 for the stack size is
  392. the suggested approach in the absence of more specific information).</p>
  393. <div class="availability docutils container">
  394. <p><a class="reference internal" href="intro.html#availability"><span class="std std-ref">Availability</span></a>: Windows, pthreads.</p>
  395. <p>Unix platforms with POSIX threads support.</p>
  396. </div>
  397. </dd></dl>
  398. <p>This module also defines the following constant:</p>
  399. <dl class="py data">
  400. <dt class="sig sig-object py" id="threading.TIMEOUT_MAX">
  401. <span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">TIMEOUT_MAX</span></span><a class="headerlink" href="#threading.TIMEOUT_MAX" title="Link to this definition">¶</a></dt>
  402. <dd><p>The maximum value allowed for the <em>timeout</em> parameter of blocking functions
  403. (<a class="reference internal" href="#threading.Lock.acquire" title="threading.Lock.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Lock.acquire()</span></code></a>, <a class="reference internal" href="#threading.RLock.acquire" title="threading.RLock.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">RLock.acquire()</span></code></a>, <a class="reference internal" href="#threading.Condition.wait" title="threading.Condition.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Condition.wait()</span></code></a>, etc.).
  404. Specifying a timeout greater than this value will raise an
  405. <a class="reference internal" href="exceptions.html#OverflowError" title="OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a>.</p>
  406. <div class="versionadded">
  407. <p><span class="versionmodified added">New in version 3.2.</span></p>
  408. </div>
  409. </dd></dl>
  410. <p>This module defines a number of classes, which are detailed in the sections
  411. below.</p>
  412. <p>The design of this module is loosely based on Java’s threading model. However,
  413. where Java makes locks and condition variables basic behavior of every object,
  414. they are separate objects in Python. Python’s <a class="reference internal" href="#threading.Thread" title="threading.Thread"><code class="xref py py-class docutils literal notranslate"><span class="pre">Thread</span></code></a> class supports a
  415. subset of the behavior of Java’s Thread class; currently, there are no
  416. priorities, no thread groups, and threads cannot be destroyed, stopped,
  417. suspended, resumed, or interrupted. The static methods of Java’s Thread class,
  418. when implemented, are mapped to module-level functions.</p>
  419. <p>All of the methods described below are executed atomically.</p>
  420. <section id="thread-local-data">
  421. <h2>Thread-Local Data<a class="headerlink" href="#thread-local-data" title="Link to this heading">¶</a></h2>
  422. <p>Thread-local data is data whose values are thread specific. To manage
  423. thread-local data, just create an instance of <a class="reference internal" href="#threading.local" title="threading.local"><code class="xref py py-class docutils literal notranslate"><span class="pre">local</span></code></a> (or a
  424. subclass) and store attributes on it:</p>
  425. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">mydata</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">local</span><span class="p">()</span>
  426. <span class="n">mydata</span><span class="o">.</span><span class="n">x</span> <span class="o">=</span> <span class="mi">1</span>
  427. </pre></div>
  428. </div>
  429. <p>The instance’s values will be different for separate threads.</p>
  430. <dl class="py class">
  431. <dt class="sig sig-object py" id="threading.local">
  432. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">local</span></span><a class="headerlink" href="#threading.local" title="Link to this definition">¶</a></dt>
  433. <dd><p>A class that represents thread-local data.</p>
  434. <p>For more details and extensive examples, see the documentation string of the
  435. <code class="xref py py-mod docutils literal notranslate"><span class="pre">_threading_local</span></code> module: <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/_threading_local.py">Lib/_threading_local.py</a>.</p>
  436. </dd></dl>
  437. </section>
  438. <section id="thread-objects">
  439. <span id="id1"></span><h2>Thread Objects<a class="headerlink" href="#thread-objects" title="Link to this heading">¶</a></h2>
  440. <p>The <a class="reference internal" href="#threading.Thread" title="threading.Thread"><code class="xref py py-class docutils literal notranslate"><span class="pre">Thread</span></code></a> class represents an activity that is run in a separate
  441. thread of control. There are two ways to specify the activity: by passing a
  442. callable object to the constructor, or by overriding the <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a>
  443. method in a subclass. No other methods (except for the constructor) should be
  444. overridden in a subclass. In other words, <em>only</em> override the
  445. <code class="docutils literal notranslate"><span class="pre">__init__()</span></code> and <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> methods of this class.</p>
  446. <p>Once a thread object is created, its activity must be started by calling the
  447. thread’s <a class="reference internal" href="#threading.Thread.start" title="threading.Thread.start"><code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code></a> method. This invokes the <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a>
  448. method in a separate thread of control.</p>
  449. <p>Once the thread’s activity is started, the thread is considered ‘alive’. It
  450. stops being alive when its <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method terminates – either
  451. normally, or by raising an unhandled exception. The <a class="reference internal" href="#threading.Thread.is_alive" title="threading.Thread.is_alive"><code class="xref py py-meth docutils literal notranslate"><span class="pre">is_alive()</span></code></a>
  452. method tests whether the thread is alive.</p>
  453. <p>Other threads can call a thread’s <a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> method. This blocks
  454. the calling thread until the thread whose <a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> method is
  455. called is terminated.</p>
  456. <p>A thread has a name. The name can be passed to the constructor, and read or
  457. changed through the <a class="reference internal" href="#threading.Thread.name" title="threading.Thread.name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code></a> attribute.</p>
  458. <p>If the <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method raises an exception,
  459. <a class="reference internal" href="#threading.excepthook" title="threading.excepthook"><code class="xref py py-func docutils literal notranslate"><span class="pre">threading.excepthook()</span></code></a> is called to handle it. By default,
  460. <a class="reference internal" href="#threading.excepthook" title="threading.excepthook"><code class="xref py py-func docutils literal notranslate"><span class="pre">threading.excepthook()</span></code></a> ignores silently <a class="reference internal" href="exceptions.html#SystemExit" title="SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a>.</p>
  461. <p>A thread can be flagged as a “daemon thread”. The significance of this flag is
  462. that the entire Python program exits when only daemon threads are left. The
  463. initial value is inherited from the creating thread. The flag can be set
  464. through the <a class="reference internal" href="#threading.Thread.daemon" title="threading.Thread.daemon"><code class="xref py py-attr docutils literal notranslate"><span class="pre">daemon</span></code></a> property or the <em>daemon</em> constructor
  465. argument.</p>
  466. <div class="admonition note">
  467. <p class="admonition-title">Note</p>
  468. <p>Daemon threads are abruptly stopped at shutdown. Their resources (such
  469. as open files, database transactions, etc.) may not be released properly.
  470. If you want your threads to stop gracefully, make them non-daemonic and
  471. use a suitable signalling mechanism such as an <a class="reference internal" href="#threading.Event" title="threading.Event"><code class="xref py py-class docutils literal notranslate"><span class="pre">Event</span></code></a>.</p>
  472. </div>
  473. <p>There is a “main thread” object; this corresponds to the initial thread of
  474. control in the Python program. It is not a daemon thread.</p>
  475. <p>There is the possibility that “dummy thread objects” are created. These are
  476. thread objects corresponding to “alien threads”, which are threads of control
  477. started outside the threading module, such as directly from C code. Dummy
  478. thread objects have limited functionality; they are always considered alive and
  479. daemonic, and cannot be <a class="reference internal" href="#meth-thread-join"><span class="std std-ref">joined</span></a>. They are never deleted,
  480. since it is impossible to detect the termination of alien threads.</p>
  481. <dl class="py class">
  482. <dt class="sig sig-object py" id="threading.Thread">
  483. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">Thread</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">group</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">target</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">name</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">args</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">()</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">kwargs</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">{}</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">daemon</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#threading.Thread" title="Link to this definition">¶</a></dt>
  484. <dd><p>This constructor should always be called with keyword arguments. Arguments
  485. are:</p>
  486. <p><em>group</em> should be <code class="docutils literal notranslate"><span class="pre">None</span></code>; reserved for future extension when a
  487. <code class="xref py py-class docutils literal notranslate"><span class="pre">ThreadGroup</span></code> class is implemented.</p>
  488. <p><em>target</em> is the callable object to be invoked by the <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method.
  489. Defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>, meaning nothing is called.</p>
  490. <p><em>name</em> is the thread name. By default, a unique name is constructed
  491. of the form “Thread-<em>N</em>” where <em>N</em> is a small decimal number,
  492. or “Thread-<em>N</em> (target)” where “target” is <code class="docutils literal notranslate"><span class="pre">target.__name__</span></code> if the
  493. <em>target</em> argument is specified.</p>
  494. <p><em>args</em> is a list or tuple of arguments for the target invocation. Defaults to <code class="docutils literal notranslate"><span class="pre">()</span></code>.</p>
  495. <p><em>kwargs</em> is a dictionary of keyword arguments for the target invocation.
  496. Defaults to <code class="docutils literal notranslate"><span class="pre">{}</span></code>.</p>
  497. <p>If not <code class="docutils literal notranslate"><span class="pre">None</span></code>, <em>daemon</em> explicitly sets whether the thread is daemonic.
  498. If <code class="docutils literal notranslate"><span class="pre">None</span></code> (the default), the daemonic property is inherited from the
  499. current thread.</p>
  500. <p>If the subclass overrides the constructor, it must make sure to invoke the
  501. base class constructor (<code class="docutils literal notranslate"><span class="pre">Thread.__init__()</span></code>) before doing anything else to
  502. the thread.</p>
  503. <div class="versionchanged">
  504. <p><span class="versionmodified changed">Changed in version 3.3: </span>Added the <em>daemon</em> parameter.</p>
  505. </div>
  506. <div class="versionchanged">
  507. <p><span class="versionmodified changed">Changed in version 3.10: </span>Use the <em>target</em> name if <em>name</em> argument is omitted.</p>
  508. </div>
  509. <dl class="py method">
  510. <dt class="sig sig-object py" id="threading.Thread.start">
  511. <span class="sig-name descname"><span class="pre">start</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Thread.start" title="Link to this definition">¶</a></dt>
  512. <dd><p>Start the thread’s activity.</p>
  513. <p>It must be called at most once per thread object. It arranges for the
  514. object’s <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method to be invoked in a separate thread
  515. of control.</p>
  516. <p>This method will raise a <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> if called more than once
  517. on the same thread object.</p>
  518. </dd></dl>
  519. <dl class="py method">
  520. <dt class="sig sig-object py" id="threading.Thread.run">
  521. <span class="sig-name descname"><span class="pre">run</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Thread.run" title="Link to this definition">¶</a></dt>
  522. <dd><p>Method representing the thread’s activity.</p>
  523. <p>You may override this method in a subclass. The standard <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a>
  524. method invokes the callable object passed to the object’s constructor as
  525. the <em>target</em> argument, if any, with positional and keyword arguments taken
  526. from the <em>args</em> and <em>kwargs</em> arguments, respectively.</p>
  527. <p>Using list or tuple as the <em>args</em> argument which passed to the <a class="reference internal" href="#threading.Thread" title="threading.Thread"><code class="xref py py-class docutils literal notranslate"><span class="pre">Thread</span></code></a>
  528. could achieve the same effect.</p>
  529. <p>Example:</p>
  530. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">threading</span> <span class="kn">import</span> <span class="n">Thread</span>
  531. <span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">Thread</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="nb">print</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>
  532. <span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">run</span><span class="p">()</span>
  533. <span class="go">1</span>
  534. <span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">Thread</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="nb">print</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="mi">1</span><span class="p">,))</span>
  535. <span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">run</span><span class="p">()</span>
  536. <span class="go">1</span>
  537. </pre></div>
  538. </div>
  539. </dd></dl>
  540. <dl class="py method" id="meth-thread-join">
  541. <dt class="sig sig-object py" id="threading.Thread.join">
  542. <span class="sig-name descname"><span class="pre">join</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#threading.Thread.join" title="Link to this definition">¶</a></dt>
  543. <dd><p>Wait until the thread terminates. This blocks the calling thread until
  544. the thread whose <a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> method is called terminates – either
  545. normally or through an unhandled exception – or until the optional
  546. timeout occurs.</p>
  547. <p>When the <em>timeout</em> argument is present and not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it should be a
  548. floating point number specifying a timeout for the operation in seconds
  549. (or fractions thereof). As <a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> always returns <code class="docutils literal notranslate"><span class="pre">None</span></code>,
  550. you must call <a class="reference internal" href="#threading.Thread.is_alive" title="threading.Thread.is_alive"><code class="xref py py-meth docutils literal notranslate"><span class="pre">is_alive()</span></code></a> after <a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> to
  551. decide whether a timeout happened – if the thread is still alive, the
  552. <a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> call timed out.</p>
  553. <p>When the <em>timeout</em> argument is not present or <code class="docutils literal notranslate"><span class="pre">None</span></code>, the operation will
  554. block until the thread terminates.</p>
  555. <p>A thread can be joined many times.</p>
  556. <p><a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> raises a <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> if an attempt is made
  557. to join the current thread as that would cause a deadlock. It is also
  558. an error to <a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> a thread before it has been started
  559. and attempts to do so raise the same exception.</p>
  560. </dd></dl>
  561. <dl class="py attribute">
  562. <dt class="sig sig-object py" id="threading.Thread.name">
  563. <span class="sig-name descname"><span class="pre">name</span></span><a class="headerlink" href="#threading.Thread.name" title="Link to this definition">¶</a></dt>
  564. <dd><p>A string used for identification purposes only. It has no semantics.
  565. Multiple threads may be given the same name. The initial name is set by
  566. the constructor.</p>
  567. </dd></dl>
  568. <dl class="py method">
  569. <dt class="sig sig-object py" id="threading.Thread.getName">
  570. <span class="sig-name descname"><span class="pre">getName</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Thread.getName" title="Link to this definition">¶</a></dt>
  571. <dt class="sig sig-object py" id="threading.Thread.setName">
  572. <span class="sig-name descname"><span class="pre">setName</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Thread.setName" title="Link to this definition">¶</a></dt>
  573. <dd><p>Deprecated getter/setter API for <a class="reference internal" href="#threading.Thread.name" title="threading.Thread.name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code></a>; use it directly as a
  574. property instead.</p>
  575. <div class="deprecated">
  576. <p><span class="versionmodified deprecated">Deprecated since version 3.10.</span></p>
  577. </div>
  578. </dd></dl>
  579. <dl class="py attribute">
  580. <dt class="sig sig-object py" id="threading.Thread.ident">
  581. <span class="sig-name descname"><span class="pre">ident</span></span><a class="headerlink" href="#threading.Thread.ident" title="Link to this definition">¶</a></dt>
  582. <dd><p>The ‘thread identifier’ of this thread or <code class="docutils literal notranslate"><span class="pre">None</span></code> if the thread has not
  583. been started. This is a nonzero integer. See the <a class="reference internal" href="#threading.get_ident" title="threading.get_ident"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_ident()</span></code></a>
  584. function. Thread identifiers may be recycled when a thread exits and
  585. another thread is created. The identifier is available even after the
  586. thread has exited.</p>
  587. </dd></dl>
  588. <dl class="py attribute">
  589. <dt class="sig sig-object py" id="threading.Thread.native_id">
  590. <span class="sig-name descname"><span class="pre">native_id</span></span><a class="headerlink" href="#threading.Thread.native_id" title="Link to this definition">¶</a></dt>
  591. <dd><p>The Thread ID (<code class="docutils literal notranslate"><span class="pre">TID</span></code>) of this thread, as assigned by the OS (kernel).
  592. This is a non-negative integer, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if the thread has not
  593. been started. See the <a class="reference internal" href="#threading.get_native_id" title="threading.get_native_id"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_native_id()</span></code></a> function.
  594. This value may be used to uniquely identify this particular thread
  595. system-wide (until the thread terminates, after which the value
  596. may be recycled by the OS).</p>
  597. <div class="admonition note">
  598. <p class="admonition-title">Note</p>
  599. <p>Similar to Process IDs, Thread IDs are only valid (guaranteed unique
  600. system-wide) from the time the thread is created until the thread
  601. has been terminated.</p>
  602. </div>
  603. <div class="availability docutils container">
  604. <p><a class="reference internal" href="intro.html#availability"><span class="std std-ref">Availability</span></a>: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX, DragonFlyBSD.</p>
  605. </div>
  606. <div class="versionadded">
  607. <p><span class="versionmodified added">New in version 3.8.</span></p>
  608. </div>
  609. </dd></dl>
  610. <dl class="py method">
  611. <dt class="sig sig-object py" id="threading.Thread.is_alive">
  612. <span class="sig-name descname"><span class="pre">is_alive</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Thread.is_alive" title="Link to this definition">¶</a></dt>
  613. <dd><p>Return whether the thread is alive.</p>
  614. <p>This method returns <code class="docutils literal notranslate"><span class="pre">True</span></code> just before the <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method
  615. starts until just after the <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method terminates. The
  616. module function <a class="reference internal" href="#threading.enumerate" title="threading.enumerate"><code class="xref py py-func docutils literal notranslate"><span class="pre">enumerate()</span></code></a> returns a list of all alive threads.</p>
  617. </dd></dl>
  618. <dl class="py attribute">
  619. <dt class="sig sig-object py" id="threading.Thread.daemon">
  620. <span class="sig-name descname"><span class="pre">daemon</span></span><a class="headerlink" href="#threading.Thread.daemon" title="Link to this definition">¶</a></dt>
  621. <dd><p>A boolean value indicating whether this thread is a daemon thread (<code class="docutils literal notranslate"><span class="pre">True</span></code>)
  622. or not (<code class="docutils literal notranslate"><span class="pre">False</span></code>). This must be set before <a class="reference internal" href="#threading.Thread.start" title="threading.Thread.start"><code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code></a> is called,
  623. otherwise <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised. Its initial value is inherited
  624. from the creating thread; the main thread is not a daemon thread and
  625. therefore all threads created in the main thread default to
  626. <a class="reference internal" href="#threading.Thread.daemon" title="threading.Thread.daemon"><code class="xref py py-attr docutils literal notranslate"><span class="pre">daemon</span></code></a> = <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
  627. <p>The entire Python program exits when no alive non-daemon threads are left.</p>
  628. </dd></dl>
  629. <dl class="py method">
  630. <dt class="sig sig-object py" id="threading.Thread.isDaemon">
  631. <span class="sig-name descname"><span class="pre">isDaemon</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Thread.isDaemon" title="Link to this definition">¶</a></dt>
  632. <dt class="sig sig-object py" id="threading.Thread.setDaemon">
  633. <span class="sig-name descname"><span class="pre">setDaemon</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Thread.setDaemon" title="Link to this definition">¶</a></dt>
  634. <dd><p>Deprecated getter/setter API for <a class="reference internal" href="#threading.Thread.daemon" title="threading.Thread.daemon"><code class="xref py py-attr docutils literal notranslate"><span class="pre">daemon</span></code></a>; use it directly as a
  635. property instead.</p>
  636. <div class="deprecated">
  637. <p><span class="versionmodified deprecated">Deprecated since version 3.10.</span></p>
  638. </div>
  639. </dd></dl>
  640. </dd></dl>
  641. </section>
  642. <section id="lock-objects">
  643. <span id="id2"></span><h2>Lock Objects<a class="headerlink" href="#lock-objects" title="Link to this heading">¶</a></h2>
  644. <p>A primitive lock is a synchronization primitive that is not owned by a
  645. particular thread when locked. In Python, it is currently the lowest level
  646. synchronization primitive available, implemented directly by the <a class="reference internal" href="_thread.html#module-_thread" title="_thread: Low-level threading API."><code class="xref py py-mod docutils literal notranslate"><span class="pre">_thread</span></code></a>
  647. extension module.</p>
  648. <p>A primitive lock is in one of two states, “locked” or “unlocked”. It is created
  649. in the unlocked state. It has two basic methods, <a class="reference internal" href="#threading.Lock.acquire" title="threading.Lock.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code></a> and
  650. <a class="reference internal" href="#threading.Lock.release" title="threading.Lock.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a>. When the state is unlocked, <a class="reference internal" href="#threading.Lock.acquire" title="threading.Lock.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code></a>
  651. changes the state to locked and returns immediately. When the state is locked,
  652. <a class="reference internal" href="#threading.Lock.acquire" title="threading.Lock.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code></a> blocks until a call to <a class="reference internal" href="#threading.Lock.release" title="threading.Lock.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a> in another
  653. thread changes it to unlocked, then the <a class="reference internal" href="#threading.Lock.acquire" title="threading.Lock.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code></a> call resets it
  654. to locked and returns. The <a class="reference internal" href="#threading.Lock.release" title="threading.Lock.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a> method should only be
  655. called in the locked state; it changes the state to unlocked and returns
  656. immediately. If an attempt is made to release an unlocked lock, a
  657. <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> will be raised.</p>
  658. <p>Locks also support the <a class="reference internal" href="#with-locks"><span class="std std-ref">context management protocol</span></a>.</p>
  659. <p>When more than one thread is blocked in <a class="reference internal" href="#threading.Lock.acquire" title="threading.Lock.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code></a> waiting for the
  660. state to turn to unlocked, only one thread proceeds when a <a class="reference internal" href="#threading.Lock.release" title="threading.Lock.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a>
  661. call resets the state to unlocked; which one of the waiting threads proceeds
  662. is not defined, and may vary across implementations.</p>
  663. <p>All methods are executed atomically.</p>
  664. <dl class="py class">
  665. <dt class="sig sig-object py" id="threading.Lock">
  666. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">Lock</span></span><a class="headerlink" href="#threading.Lock" title="Link to this definition">¶</a></dt>
  667. <dd><p>The class implementing primitive lock objects. Once a thread has acquired a
  668. lock, subsequent attempts to acquire it block, until it is released; any
  669. thread may release it.</p>
  670. <p>Note that <code class="docutils literal notranslate"><span class="pre">Lock</span></code> is actually a factory function which returns an instance
  671. of the most efficient version of the concrete Lock class that is supported
  672. by the platform.</p>
  673. <dl class="py method">
  674. <dt class="sig sig-object py" id="threading.Lock.acquire">
  675. <span class="sig-name descname"><span class="pre">acquire</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">blocking</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">-1</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#threading.Lock.acquire" title="Link to this definition">¶</a></dt>
  676. <dd><p>Acquire a lock, blocking or non-blocking.</p>
  677. <p>When invoked with the <em>blocking</em> argument set to <code class="docutils literal notranslate"><span class="pre">True</span></code> (the default),
  678. block until the lock is unlocked, then set it to locked and return <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
  679. <p>When invoked with the <em>blocking</em> argument set to <code class="docutils literal notranslate"><span class="pre">False</span></code>, do not block.
  680. If a call with <em>blocking</em> set to <code class="docutils literal notranslate"><span class="pre">True</span></code> would block, return <code class="docutils literal notranslate"><span class="pre">False</span></code>
  681. immediately; otherwise, set the lock to locked and return <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
  682. <p>When invoked with the floating-point <em>timeout</em> argument set to a positive
  683. value, block for at most the number of seconds specified by <em>timeout</em>
  684. and as long as the lock cannot be acquired. A <em>timeout</em> argument of <code class="docutils literal notranslate"><span class="pre">-1</span></code>
  685. specifies an unbounded wait. It is forbidden to specify a <em>timeout</em>
  686. when <em>blocking</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
  687. <p>The return value is <code class="docutils literal notranslate"><span class="pre">True</span></code> if the lock is acquired successfully,
  688. <code class="docutils literal notranslate"><span class="pre">False</span></code> if not (for example if the <em>timeout</em> expired).</p>
  689. <div class="versionchanged">
  690. <p><span class="versionmodified changed">Changed in version 3.2: </span>The <em>timeout</em> parameter is new.</p>
  691. </div>
  692. <div class="versionchanged">
  693. <p><span class="versionmodified changed">Changed in version 3.2: </span>Lock acquisition can now be interrupted by signals on POSIX if the
  694. underlying threading implementation supports it.</p>
  695. </div>
  696. </dd></dl>
  697. <dl class="py method">
  698. <dt class="sig sig-object py" id="threading.Lock.release">
  699. <span class="sig-name descname"><span class="pre">release</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Lock.release" title="Link to this definition">¶</a></dt>
  700. <dd><p>Release a lock. This can be called from any thread, not only the thread
  701. which has acquired the lock.</p>
  702. <p>When the lock is locked, reset it to unlocked, and return. If any other threads
  703. are blocked waiting for the lock to become unlocked, allow exactly one of them
  704. to proceed.</p>
  705. <p>When invoked on an unlocked lock, a <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised.</p>
  706. <p>There is no return value.</p>
  707. </dd></dl>
  708. <dl class="py method">
  709. <dt class="sig sig-object py" id="threading.Lock.locked">
  710. <span class="sig-name descname"><span class="pre">locked</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Lock.locked" title="Link to this definition">¶</a></dt>
  711. <dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the lock is acquired.</p>
  712. </dd></dl>
  713. </dd></dl>
  714. </section>
  715. <section id="rlock-objects">
  716. <span id="id3"></span><h2>RLock Objects<a class="headerlink" href="#rlock-objects" title="Link to this heading">¶</a></h2>
  717. <p>A reentrant lock is a synchronization primitive that may be acquired multiple
  718. times by the same thread. Internally, it uses the concepts of “owning thread”
  719. and “recursion level” in addition to the locked/unlocked state used by primitive
  720. locks. In the locked state, some thread owns the lock; in the unlocked state,
  721. no thread owns it.</p>
  722. <p>To lock the lock, a thread calls its <a class="reference internal" href="#threading.RLock.acquire" title="threading.RLock.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code></a> method; this
  723. returns once the thread owns the lock. To unlock the lock, a thread calls
  724. its <a class="reference internal" href="#threading.Lock.release" title="threading.Lock.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a> method. <a class="reference internal" href="#threading.Lock.acquire" title="threading.Lock.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code></a>/<a class="reference internal" href="#threading.Lock.release" title="threading.Lock.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a>
  725. call pairs may be nested; only the final <a class="reference internal" href="#threading.Lock.release" title="threading.Lock.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a> (the
  726. <a class="reference internal" href="#threading.Lock.release" title="threading.Lock.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a> of the outermost pair) resets the lock to unlocked and
  727. allows another thread blocked in <a class="reference internal" href="#threading.Lock.acquire" title="threading.Lock.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code></a> to proceed.</p>
  728. <p>Reentrant locks also support the <a class="reference internal" href="#with-locks"><span class="std std-ref">context management protocol</span></a>.</p>
  729. <dl class="py class">
  730. <dt class="sig sig-object py" id="threading.RLock">
  731. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">RLock</span></span><a class="headerlink" href="#threading.RLock" title="Link to this definition">¶</a></dt>
  732. <dd><p>This class implements reentrant lock objects. A reentrant lock must be
  733. released by the thread that acquired it. Once a thread has acquired a
  734. reentrant lock, the same thread may acquire it again without blocking; the
  735. thread must release it once for each time it has acquired it.</p>
  736. <p>Note that <code class="docutils literal notranslate"><span class="pre">RLock</span></code> is actually a factory function which returns an instance
  737. of the most efficient version of the concrete RLock class that is supported
  738. by the platform.</p>
  739. <dl class="py method">
  740. <dt class="sig sig-object py" id="threading.RLock.acquire">
  741. <span class="sig-name descname"><span class="pre">acquire</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">blocking</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">-1</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#threading.RLock.acquire" title="Link to this definition">¶</a></dt>
  742. <dd><p>Acquire a lock, blocking or non-blocking.</p>
  743. <p>When invoked without arguments: if this thread already owns the lock, increment
  744. the recursion level by one, and return immediately. Otherwise, if another
  745. thread owns the lock, block until the lock is unlocked. Once the lock is
  746. unlocked (not owned by any thread), then grab ownership, set the recursion level
  747. to one, and return. If more than one thread is blocked waiting until the lock
  748. is unlocked, only one at a time will be able to grab ownership of the lock.
  749. There is no return value in this case.</p>
  750. <p>When invoked with the <em>blocking</em> argument set to <code class="docutils literal notranslate"><span class="pre">True</span></code>, do the same thing as when
  751. called without arguments, and return <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
  752. <p>When invoked with the <em>blocking</em> argument set to <code class="docutils literal notranslate"><span class="pre">False</span></code>, do not block. If a call
  753. without an argument would block, return <code class="docutils literal notranslate"><span class="pre">False</span></code> immediately; otherwise, do the
  754. same thing as when called without arguments, and return <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
  755. <p>When invoked with the floating-point <em>timeout</em> argument set to a positive
  756. value, block for at most the number of seconds specified by <em>timeout</em>
  757. and as long as the lock cannot be acquired. Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the lock has
  758. been acquired, <code class="docutils literal notranslate"><span class="pre">False</span></code> if the timeout has elapsed.</p>
  759. <div class="versionchanged">
  760. <p><span class="versionmodified changed">Changed in version 3.2: </span>The <em>timeout</em> parameter is new.</p>
  761. </div>
  762. </dd></dl>
  763. <dl class="py method">
  764. <dt class="sig sig-object py" id="threading.RLock.release">
  765. <span class="sig-name descname"><span class="pre">release</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.RLock.release" title="Link to this definition">¶</a></dt>
  766. <dd><p>Release a lock, decrementing the recursion level. If after the decrement it is
  767. zero, reset the lock to unlocked (not owned by any thread), and if any other
  768. threads are blocked waiting for the lock to become unlocked, allow exactly one
  769. of them to proceed. If after the decrement the recursion level is still
  770. nonzero, the lock remains locked and owned by the calling thread.</p>
  771. <p>Only call this method when the calling thread owns the lock. A
  772. <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised if this method is called when the lock is
  773. unlocked.</p>
  774. <p>There is no return value.</p>
  775. </dd></dl>
  776. </dd></dl>
  777. </section>
  778. <section id="condition-objects">
  779. <span id="id4"></span><h2>Condition Objects<a class="headerlink" href="#condition-objects" title="Link to this heading">¶</a></h2>
  780. <p>A condition variable is always associated with some kind of lock; this can be
  781. passed in or one will be created by default. Passing one in is useful when
  782. several condition variables must share the same lock. The lock is part of
  783. the condition object: you don’t have to track it separately.</p>
  784. <p>A condition variable obeys the <a class="reference internal" href="#with-locks"><span class="std std-ref">context management protocol</span></a>:
  785. using the <code class="docutils literal notranslate"><span class="pre">with</span></code> statement acquires the associated lock for the duration of
  786. the enclosed block. The <a class="reference internal" href="#threading.Condition.acquire" title="threading.Condition.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code></a> and
  787. <a class="reference internal" href="#threading.Condition.release" title="threading.Condition.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a> methods also call the corresponding methods of
  788. the associated lock.</p>
  789. <p>Other methods must be called with the associated lock held. The
  790. <a class="reference internal" href="#threading.Condition.wait" title="threading.Condition.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> method releases the lock, and then blocks until
  791. another thread awakens it by calling <a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify()</span></code></a> or
  792. <a class="reference internal" href="#threading.Condition.notify_all" title="threading.Condition.notify_all"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify_all()</span></code></a>. Once awakened, <a class="reference internal" href="#threading.Condition.wait" title="threading.Condition.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a>
  793. re-acquires the lock and returns. It is also possible to specify a timeout.</p>
  794. <p>The <a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify()</span></code></a> method wakes up one of the threads waiting for
  795. the condition variable, if any are waiting. The <a class="reference internal" href="#threading.Condition.notify_all" title="threading.Condition.notify_all"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify_all()</span></code></a>
  796. method wakes up all threads waiting for the condition variable.</p>
  797. <p>Note: the <a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify()</span></code></a> and <a class="reference internal" href="#threading.Condition.notify_all" title="threading.Condition.notify_all"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify_all()</span></code></a> methods
  798. don’t release the lock; this means that the thread or threads awakened will
  799. not return from their <a class="reference internal" href="#threading.Condition.wait" title="threading.Condition.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> call immediately, but only when
  800. the thread that called <a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify()</span></code></a> or <a class="reference internal" href="#threading.Condition.notify_all" title="threading.Condition.notify_all"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify_all()</span></code></a>
  801. finally relinquishes ownership of the lock.</p>
  802. <p>The typical programming style using condition variables uses the lock to
  803. synchronize access to some shared state; threads that are interested in a
  804. particular change of state call <a class="reference internal" href="#threading.Condition.wait" title="threading.Condition.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> repeatedly until they
  805. see the desired state, while threads that modify the state call
  806. <a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify()</span></code></a> or <a class="reference internal" href="#threading.Condition.notify_all" title="threading.Condition.notify_all"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify_all()</span></code></a> when they change
  807. the state in such a way that it could possibly be a desired state for one
  808. of the waiters. For example, the following code is a generic
  809. producer-consumer situation with unlimited buffer capacity:</p>
  810. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Consume one item</span>
  811. <span class="k">with</span> <span class="n">cv</span><span class="p">:</span>
  812. <span class="k">while</span> <span class="ow">not</span> <span class="n">an_item_is_available</span><span class="p">():</span>
  813. <span class="n">cv</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>
  814. <span class="n">get_an_available_item</span><span class="p">()</span>
  815. <span class="c1"># Produce one item</span>
  816. <span class="k">with</span> <span class="n">cv</span><span class="p">:</span>
  817. <span class="n">make_an_item_available</span><span class="p">()</span>
  818. <span class="n">cv</span><span class="o">.</span><span class="n">notify</span><span class="p">()</span>
  819. </pre></div>
  820. </div>
  821. <p>The <code class="docutils literal notranslate"><span class="pre">while</span></code> loop checking for the application’s condition is necessary
  822. because <a class="reference internal" href="#threading.Condition.wait" title="threading.Condition.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> can return after an arbitrary long time,
  823. and the condition which prompted the <a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify()</span></code></a> call may
  824. no longer hold true. This is inherent to multi-threaded programming. The
  825. <a class="reference internal" href="#threading.Condition.wait_for" title="threading.Condition.wait_for"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait_for()</span></code></a> method can be used to automate the condition
  826. checking, and eases the computation of timeouts:</p>
  827. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Consume an item</span>
  828. <span class="k">with</span> <span class="n">cv</span><span class="p">:</span>
  829. <span class="n">cv</span><span class="o">.</span><span class="n">wait_for</span><span class="p">(</span><span class="n">an_item_is_available</span><span class="p">)</span>
  830. <span class="n">get_an_available_item</span><span class="p">()</span>
  831. </pre></div>
  832. </div>
  833. <p>To choose between <a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify()</span></code></a> and <a class="reference internal" href="#threading.Condition.notify_all" title="threading.Condition.notify_all"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify_all()</span></code></a>,
  834. consider whether one state change can be interesting for only one or several
  835. waiting threads. E.g. in a typical producer-consumer situation, adding one
  836. item to the buffer only needs to wake up one consumer thread.</p>
  837. <dl class="py class">
  838. <dt class="sig sig-object py" id="threading.Condition">
  839. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">Condition</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">lock</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#threading.Condition" title="Link to this definition">¶</a></dt>
  840. <dd><p>This class implements condition variable objects. A condition variable
  841. allows one or more threads to wait until they are notified by another thread.</p>
  842. <p>If the <em>lock</em> argument is given and not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it must be a <a class="reference internal" href="#threading.Lock" title="threading.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Lock</span></code></a>
  843. or <a class="reference internal" href="#threading.RLock" title="threading.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">RLock</span></code></a> object, and it is used as the underlying lock. Otherwise,
  844. a new <a class="reference internal" href="#threading.RLock" title="threading.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">RLock</span></code></a> object is created and used as the underlying lock.</p>
  845. <div class="versionchanged">
  846. <p><span class="versionmodified changed">Changed in version 3.3: </span>changed from a factory function to a class.</p>
  847. </div>
  848. <dl class="py method">
  849. <dt class="sig sig-object py" id="threading.Condition.acquire">
  850. <span class="sig-name descname"><span class="pre">acquire</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#threading.Condition.acquire" title="Link to this definition">¶</a></dt>
  851. <dd><p>Acquire the underlying lock. This method calls the corresponding method on
  852. the underlying lock; the return value is whatever that method returns.</p>
  853. </dd></dl>
  854. <dl class="py method">
  855. <dt class="sig sig-object py" id="threading.Condition.release">
  856. <span class="sig-name descname"><span class="pre">release</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Condition.release" title="Link to this definition">¶</a></dt>
  857. <dd><p>Release the underlying lock. This method calls the corresponding method on
  858. the underlying lock; there is no return value.</p>
  859. </dd></dl>
  860. <dl class="py method">
  861. <dt class="sig sig-object py" id="threading.Condition.wait">
  862. <span class="sig-name descname"><span class="pre">wait</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#threading.Condition.wait" title="Link to this definition">¶</a></dt>
  863. <dd><p>Wait until notified or until a timeout occurs. If the calling thread has
  864. not acquired the lock when this method is called, a <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is
  865. raised.</p>
  866. <p>This method releases the underlying lock, and then blocks until it is
  867. awakened by a <a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify()</span></code></a> or <a class="reference internal" href="#threading.Condition.notify_all" title="threading.Condition.notify_all"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify_all()</span></code></a> call for the same
  868. condition variable in another thread, or until the optional timeout
  869. occurs. Once awakened or timed out, it re-acquires the lock and returns.</p>
  870. <p>When the <em>timeout</em> argument is present and not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it should be a
  871. floating point number specifying a timeout for the operation in seconds
  872. (or fractions thereof).</p>
  873. <p>When the underlying lock is an <a class="reference internal" href="#threading.RLock" title="threading.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">RLock</span></code></a>, it is not released using
  874. its <a class="reference internal" href="#threading.Condition.release" title="threading.Condition.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a> method, since this may not actually unlock the lock
  875. when it was acquired multiple times recursively. Instead, an internal
  876. interface of the <a class="reference internal" href="#threading.RLock" title="threading.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">RLock</span></code></a> class is used, which really unlocks it
  877. even when it has been recursively acquired several times. Another internal
  878. interface is then used to restore the recursion level when the lock is
  879. reacquired.</p>
  880. <p>The return value is <code class="docutils literal notranslate"><span class="pre">True</span></code> unless a given <em>timeout</em> expired, in which
  881. case it is <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
  882. <div class="versionchanged">
  883. <p><span class="versionmodified changed">Changed in version 3.2: </span>Previously, the method always returned <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
  884. </div>
  885. </dd></dl>
  886. <dl class="py method">
  887. <dt class="sig sig-object py" id="threading.Condition.wait_for">
  888. <span class="sig-name descname"><span class="pre">wait_for</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">predicate</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#threading.Condition.wait_for" title="Link to this definition">¶</a></dt>
  889. <dd><p>Wait until a condition evaluates to true. <em>predicate</em> should be a
  890. callable which result will be interpreted as a boolean value.
  891. A <em>timeout</em> may be provided giving the maximum time to wait.</p>
  892. <p>This utility method may call <a class="reference internal" href="#threading.Condition.wait" title="threading.Condition.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> repeatedly until the predicate
  893. is satisfied, or until a timeout occurs. The return value is
  894. the last return value of the predicate and will evaluate to
  895. <code class="docutils literal notranslate"><span class="pre">False</span></code> if the method timed out.</p>
  896. <p>Ignoring the timeout feature, calling this method is roughly equivalent to
  897. writing:</p>
  898. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">while</span> <span class="ow">not</span> <span class="n">predicate</span><span class="p">():</span>
  899. <span class="n">cv</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>
  900. </pre></div>
  901. </div>
  902. <p>Therefore, the same rules apply as with <a class="reference internal" href="#threading.Condition.wait" title="threading.Condition.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a>: The lock must be
  903. held when called and is re-acquired on return. The predicate is evaluated
  904. with the lock held.</p>
  905. <div class="versionadded">
  906. <p><span class="versionmodified added">New in version 3.2.</span></p>
  907. </div>
  908. </dd></dl>
  909. <dl class="py method">
  910. <dt class="sig sig-object py" id="threading.Condition.notify">
  911. <span class="sig-name descname"><span class="pre">notify</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">n</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">1</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#threading.Condition.notify" title="Link to this definition">¶</a></dt>
  912. <dd><p>By default, wake up one thread waiting on this condition, if any. If the
  913. calling thread has not acquired the lock when this method is called, a
  914. <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised.</p>
  915. <p>This method wakes up at most <em>n</em> of the threads waiting for the condition
  916. variable; it is a no-op if no threads are waiting.</p>
  917. <p>The current implementation wakes up exactly <em>n</em> threads, if at least <em>n</em>
  918. threads are waiting. However, it’s not safe to rely on this behavior.
  919. A future, optimized implementation may occasionally wake up more than
  920. <em>n</em> threads.</p>
  921. <p>Note: an awakened thread does not actually return from its <a class="reference internal" href="#threading.Condition.wait" title="threading.Condition.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a>
  922. call until it can reacquire the lock. Since <a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify()</span></code></a> does not
  923. release the lock, its caller should.</p>
  924. </dd></dl>
  925. <dl class="py method">
  926. <dt class="sig sig-object py" id="threading.Condition.notify_all">
  927. <span class="sig-name descname"><span class="pre">notify_all</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Condition.notify_all" title="Link to this definition">¶</a></dt>
  928. <dd><p>Wake up all threads waiting on this condition. This method acts like
  929. <a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify()</span></code></a>, but wakes up all waiting threads instead of one. If the
  930. calling thread has not acquired the lock when this method is called, a
  931. <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised.</p>
  932. <p>The method <code class="docutils literal notranslate"><span class="pre">notifyAll</span></code> is a deprecated alias for this method.</p>
  933. </dd></dl>
  934. </dd></dl>
  935. </section>
  936. <section id="semaphore-objects">
  937. <span id="id5"></span><h2>Semaphore Objects<a class="headerlink" href="#semaphore-objects" title="Link to this heading">¶</a></h2>
  938. <p>This is one of the oldest synchronization primitives in the history of computer
  939. science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he
  940. used the names <code class="docutils literal notranslate"><span class="pre">P()</span></code> and <code class="docutils literal notranslate"><span class="pre">V()</span></code> instead of <a class="reference internal" href="#threading.Semaphore.acquire" title="threading.Semaphore.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code></a> and
  941. <a class="reference internal" href="#threading.Semaphore.release" title="threading.Semaphore.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a>).</p>
  942. <p>A semaphore manages an internal counter which is decremented by each
  943. <a class="reference internal" href="#threading.Semaphore.acquire" title="threading.Semaphore.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code></a> call and incremented by each <a class="reference internal" href="#threading.Semaphore.release" title="threading.Semaphore.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a>
  944. call. The counter can never go below zero; when <a class="reference internal" href="#threading.Semaphore.acquire" title="threading.Semaphore.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code></a>
  945. finds that it is zero, it blocks, waiting until some other thread calls
  946. <a class="reference internal" href="#threading.Semaphore.release" title="threading.Semaphore.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a>.</p>
  947. <p>Semaphores also support the <a class="reference internal" href="#with-locks"><span class="std std-ref">context management protocol</span></a>.</p>
  948. <dl class="py class">
  949. <dt class="sig sig-object py" id="threading.Semaphore">
  950. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">Semaphore</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">value</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">1</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#threading.Semaphore" title="Link to this definition">¶</a></dt>
  951. <dd><p>This class implements semaphore objects. A semaphore manages an atomic
  952. counter representing the number of <a class="reference internal" href="#threading.Semaphore.release" title="threading.Semaphore.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a> calls minus the number of
  953. <a class="reference internal" href="#threading.Semaphore.acquire" title="threading.Semaphore.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code></a> calls, plus an initial value. The <a class="reference internal" href="#threading.Semaphore.acquire" title="threading.Semaphore.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code></a> method
  954. blocks if necessary until it can return without making the counter negative.
  955. If not given, <em>value</em> defaults to 1.</p>
  956. <p>The optional argument gives the initial <em>value</em> for the internal counter; it
  957. defaults to <code class="docutils literal notranslate"><span class="pre">1</span></code>. If the <em>value</em> given is less than 0, <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> is
  958. raised.</p>
  959. <div class="versionchanged">
  960. <p><span class="versionmodified changed">Changed in version 3.3: </span>changed from a factory function to a class.</p>
  961. </div>
  962. <dl class="py method">
  963. <dt class="sig sig-object py" id="threading.Semaphore.acquire">
  964. <span class="sig-name descname"><span class="pre">acquire</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">blocking</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#threading.Semaphore.acquire" title="Link to this definition">¶</a></dt>
  965. <dd><p>Acquire a semaphore.</p>
  966. <p>When invoked without arguments:</p>
  967. <ul class="simple">
  968. <li><p>If the internal counter is larger than zero on entry, decrement it by
  969. one and return <code class="docutils literal notranslate"><span class="pre">True</span></code> immediately.</p></li>
  970. <li><p>If the internal counter is zero on entry, block until awoken by a call to
  971. <a class="reference internal" href="#threading.Semaphore.release" title="threading.Semaphore.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a>. Once awoken (and the counter is greater
  972. than 0), decrement the counter by 1 and return <code class="docutils literal notranslate"><span class="pre">True</span></code>. Exactly one
  973. thread will be awoken by each call to <a class="reference internal" href="#threading.Semaphore.release" title="threading.Semaphore.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a>. The
  974. order in which threads are awoken should not be relied on.</p></li>
  975. </ul>
  976. <p>When invoked with <em>blocking</em> set to <code class="docutils literal notranslate"><span class="pre">False</span></code>, do not block. If a call
  977. without an argument would block, return <code class="docutils literal notranslate"><span class="pre">False</span></code> immediately; otherwise, do
  978. the same thing as when called without arguments, and return <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
  979. <p>When invoked with a <em>timeout</em> other than <code class="docutils literal notranslate"><span class="pre">None</span></code>, it will block for at
  980. most <em>timeout</em> seconds. If acquire does not complete successfully in
  981. that interval, return <code class="docutils literal notranslate"><span class="pre">False</span></code>. Return <code class="docutils literal notranslate"><span class="pre">True</span></code> otherwise.</p>
  982. <div class="versionchanged">
  983. <p><span class="versionmodified changed">Changed in version 3.2: </span>The <em>timeout</em> parameter is new.</p>
  984. </div>
  985. </dd></dl>
  986. <dl class="py method">
  987. <dt class="sig sig-object py" id="threading.Semaphore.release">
  988. <span class="sig-name descname"><span class="pre">release</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">n</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">1</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#threading.Semaphore.release" title="Link to this definition">¶</a></dt>
  989. <dd><p>Release a semaphore, incrementing the internal counter by <em>n</em>. When it
  990. was zero on entry and other threads are waiting for it to become larger
  991. than zero again, wake up <em>n</em> of those threads.</p>
  992. <div class="versionchanged">
  993. <p><span class="versionmodified changed">Changed in version 3.9: </span>Added the <em>n</em> parameter to release multiple waiting threads at once.</p>
  994. </div>
  995. </dd></dl>
  996. </dd></dl>
  997. <dl class="py class">
  998. <dt class="sig sig-object py" id="threading.BoundedSemaphore">
  999. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">BoundedSemaphore</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">value</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">1</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#threading.BoundedSemaphore" title="Link to this definition">¶</a></dt>
  1000. <dd><p>Class implementing bounded semaphore objects. A bounded semaphore checks to
  1001. make sure its current value doesn’t exceed its initial value. If it does,
  1002. <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> is raised. In most situations semaphores are used to guard
  1003. resources with limited capacity. If the semaphore is released too many times
  1004. it’s a sign of a bug. If not given, <em>value</em> defaults to 1.</p>
  1005. <div class="versionchanged">
  1006. <p><span class="versionmodified changed">Changed in version 3.3: </span>changed from a factory function to a class.</p>
  1007. </div>
  1008. </dd></dl>
  1009. <section id="semaphore-example">
  1010. <span id="semaphore-examples"></span><h3><a class="reference internal" href="#threading.Semaphore" title="threading.Semaphore"><code class="xref py py-class docutils literal notranslate"><span class="pre">Semaphore</span></code></a> Example<a class="headerlink" href="#semaphore-example" title="Link to this heading">¶</a></h3>
  1011. <p>Semaphores are often used to guard resources with limited capacity, for example,
  1012. a database server. In any situation where the size of the resource is fixed,
  1013. you should use a bounded semaphore. Before spawning any worker threads, your
  1014. main thread would initialize the semaphore:</p>
  1015. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">maxconnections</span> <span class="o">=</span> <span class="mi">5</span>
  1016. <span class="c1"># ...</span>
  1017. <span class="n">pool_sema</span> <span class="o">=</span> <span class="n">BoundedSemaphore</span><span class="p">(</span><span class="n">value</span><span class="o">=</span><span class="n">maxconnections</span><span class="p">)</span>
  1018. </pre></div>
  1019. </div>
  1020. <p>Once spawned, worker threads call the semaphore’s acquire and release methods
  1021. when they need to connect to the server:</p>
  1022. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">pool_sema</span><span class="p">:</span>
  1023. <span class="n">conn</span> <span class="o">=</span> <span class="n">connectdb</span><span class="p">()</span>
  1024. <span class="k">try</span><span class="p">:</span>
  1025. <span class="c1"># ... use connection ...</span>
  1026. <span class="k">finally</span><span class="p">:</span>
  1027. <span class="n">conn</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
  1028. </pre></div>
  1029. </div>
  1030. <p>The use of a bounded semaphore reduces the chance that a programming error which
  1031. causes the semaphore to be released more than it’s acquired will go undetected.</p>
  1032. </section>
  1033. </section>
  1034. <section id="event-objects">
  1035. <span id="id6"></span><h2>Event Objects<a class="headerlink" href="#event-objects" title="Link to this heading">¶</a></h2>
  1036. <p>This is one of the simplest mechanisms for communication between threads: one
  1037. thread signals an event and other threads wait for it.</p>
  1038. <p>An event object manages an internal flag that can be set to true with the
  1039. <a class="reference internal" href="#threading.Event.set" title="threading.Event.set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set()</span></code></a> method and reset to false with the <a class="reference internal" href="#threading.Event.clear" title="threading.Event.clear"><code class="xref py py-meth docutils literal notranslate"><span class="pre">clear()</span></code></a>
  1040. method. The <a class="reference internal" href="#threading.Event.wait" title="threading.Event.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> method blocks until the flag is true.</p>
  1041. <dl class="py class">
  1042. <dt class="sig sig-object py" id="threading.Event">
  1043. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">Event</span></span><a class="headerlink" href="#threading.Event" title="Link to this definition">¶</a></dt>
  1044. <dd><p>Class implementing event objects. An event manages a flag that can be set to
  1045. true with the <a class="reference internal" href="#threading.Event.set" title="threading.Event.set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set()</span></code></a> method and reset to false with the
  1046. <a class="reference internal" href="#threading.Event.clear" title="threading.Event.clear"><code class="xref py py-meth docutils literal notranslate"><span class="pre">clear()</span></code></a> method. The <a class="reference internal" href="#threading.Event.wait" title="threading.Event.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> method blocks until the flag is true.
  1047. The flag is initially false.</p>
  1048. <div class="versionchanged">
  1049. <p><span class="versionmodified changed">Changed in version 3.3: </span>changed from a factory function to a class.</p>
  1050. </div>
  1051. <dl class="py method">
  1052. <dt class="sig sig-object py" id="threading.Event.is_set">
  1053. <span class="sig-name descname"><span class="pre">is_set</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Event.is_set" title="Link to this definition">¶</a></dt>
  1054. <dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if and only if the internal flag is true.</p>
  1055. <p>The method <code class="docutils literal notranslate"><span class="pre">isSet</span></code> is a deprecated alias for this method.</p>
  1056. </dd></dl>
  1057. <dl class="py method">
  1058. <dt class="sig sig-object py" id="threading.Event.set">
  1059. <span class="sig-name descname"><span class="pre">set</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Event.set" title="Link to this definition">¶</a></dt>
  1060. <dd><p>Set the internal flag to true. All threads waiting for it to become true
  1061. are awakened. Threads that call <a class="reference internal" href="#threading.Event.wait" title="threading.Event.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> once the flag is true will
  1062. not block at all.</p>
  1063. </dd></dl>
  1064. <dl class="py method">
  1065. <dt class="sig sig-object py" id="threading.Event.clear">
  1066. <span class="sig-name descname"><span class="pre">clear</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Event.clear" title="Link to this definition">¶</a></dt>
  1067. <dd><p>Reset the internal flag to false. Subsequently, threads calling
  1068. <a class="reference internal" href="#threading.Event.wait" title="threading.Event.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> will block until <a class="reference internal" href="#threading.Event.set" title="threading.Event.set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set()</span></code></a> is called to set the internal
  1069. flag to true again.</p>
  1070. </dd></dl>
  1071. <dl class="py method">
  1072. <dt class="sig sig-object py" id="threading.Event.wait">
  1073. <span class="sig-name descname"><span class="pre">wait</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#threading.Event.wait" title="Link to this definition">¶</a></dt>
  1074. <dd><p>Block as long as the internal flag is false and the timeout, if given,
  1075. has not expired. The return value represents the
  1076. reason that this blocking method returned; <code class="docutils literal notranslate"><span class="pre">True</span></code> if returning because
  1077. the internal flag is set to true, or <code class="docutils literal notranslate"><span class="pre">False</span></code> if a timeout is given and
  1078. the the internal flag did not become true within the given wait time.</p>
  1079. <p>When the timeout argument is present and not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it should be a
  1080. floating point number specifying a timeout for the operation in seconds,
  1081. or fractions thereof.</p>
  1082. <div class="versionchanged">
  1083. <p><span class="versionmodified changed">Changed in version 3.1: </span>Previously, the method always returned <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
  1084. </div>
  1085. </dd></dl>
  1086. </dd></dl>
  1087. </section>
  1088. <section id="timer-objects">
  1089. <span id="id7"></span><h2>Timer Objects<a class="headerlink" href="#timer-objects" title="Link to this heading">¶</a></h2>
  1090. <p>This class represents an action that should be run only after a certain amount
  1091. of time has passed — a timer. <a class="reference internal" href="#threading.Timer" title="threading.Timer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Timer</span></code></a> is a subclass of <a class="reference internal" href="#threading.Thread" title="threading.Thread"><code class="xref py py-class docutils literal notranslate"><span class="pre">Thread</span></code></a>
  1092. and as such also functions as an example of creating custom threads.</p>
  1093. <p>Timers are started, as with threads, by calling their <a class="reference internal" href="#threading.Thread.start" title="threading.Thread.start"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Timer.start</span></code></a>
  1094. method. The timer can be stopped (before its action has begun) by calling the
  1095. <a class="reference internal" href="#threading.Timer.cancel" title="threading.Timer.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cancel()</span></code></a> method. The interval the timer will wait before
  1096. executing its action may not be exactly the same as the interval specified by
  1097. the user.</p>
  1098. <p>For example:</p>
  1099. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">hello</span><span class="p">():</span>
  1100. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;hello, world&quot;</span><span class="p">)</span>
  1101. <span class="n">t</span> <span class="o">=</span> <span class="n">Timer</span><span class="p">(</span><span class="mf">30.0</span><span class="p">,</span> <span class="n">hello</span><span class="p">)</span>
  1102. <span class="n">t</span><span class="o">.</span><span class="n">start</span><span class="p">()</span> <span class="c1"># after 30 seconds, &quot;hello, world&quot; will be printed</span>
  1103. </pre></div>
  1104. </div>
  1105. <dl class="py class">
  1106. <dt class="sig sig-object py" id="threading.Timer">
  1107. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">Timer</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">interval</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">function</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">args</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">kwargs</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#threading.Timer" title="Link to this definition">¶</a></dt>
  1108. <dd><p>Create a timer that will run <em>function</em> with arguments <em>args</em> and keyword
  1109. arguments <em>kwargs</em>, after <em>interval</em> seconds have passed.
  1110. If <em>args</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> (the default) then an empty list will be used.
  1111. If <em>kwargs</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> (the default) then an empty dict will be used.</p>
  1112. <div class="versionchanged">
  1113. <p><span class="versionmodified changed">Changed in version 3.3: </span>changed from a factory function to a class.</p>
  1114. </div>
  1115. <dl class="py method">
  1116. <dt class="sig sig-object py" id="threading.Timer.cancel">
  1117. <span class="sig-name descname"><span class="pre">cancel</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Timer.cancel" title="Link to this definition">¶</a></dt>
  1118. <dd><p>Stop the timer, and cancel the execution of the timer’s action. This will
  1119. only work if the timer is still in its waiting stage.</p>
  1120. </dd></dl>
  1121. </dd></dl>
  1122. </section>
  1123. <section id="barrier-objects">
  1124. <h2>Barrier Objects<a class="headerlink" href="#barrier-objects" title="Link to this heading">¶</a></h2>
  1125. <div class="versionadded">
  1126. <p><span class="versionmodified added">New in version 3.2.</span></p>
  1127. </div>
  1128. <p>This class provides a simple synchronization primitive for use by a fixed number
  1129. of threads that need to wait for each other. Each of the threads tries to pass
  1130. the barrier by calling the <a class="reference internal" href="#threading.Barrier.wait" title="threading.Barrier.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> method and will block until
  1131. all of the threads have made their <a class="reference internal" href="#threading.Barrier.wait" title="threading.Barrier.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> calls. At this point,
  1132. the threads are released simultaneously.</p>
  1133. <p>The barrier can be reused any number of times for the same number of threads.</p>
  1134. <p>As an example, here is a simple way to synchronize a client and server thread:</p>
  1135. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">b</span> <span class="o">=</span> <span class="n">Barrier</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">timeout</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>
  1136. <span class="k">def</span> <span class="nf">server</span><span class="p">():</span>
  1137. <span class="n">start_server</span><span class="p">()</span>
  1138. <span class="n">b</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>
  1139. <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
  1140. <span class="n">connection</span> <span class="o">=</span> <span class="n">accept_connection</span><span class="p">()</span>
  1141. <span class="n">process_server_connection</span><span class="p">(</span><span class="n">connection</span><span class="p">)</span>
  1142. <span class="k">def</span> <span class="nf">client</span><span class="p">():</span>
  1143. <span class="n">b</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>
  1144. <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
  1145. <span class="n">connection</span> <span class="o">=</span> <span class="n">make_connection</span><span class="p">()</span>
  1146. <span class="n">process_client_connection</span><span class="p">(</span><span class="n">connection</span><span class="p">)</span>
  1147. </pre></div>
  1148. </div>
  1149. <dl class="py class">
  1150. <dt class="sig sig-object py" id="threading.Barrier">
  1151. <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">Barrier</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">parties</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">action</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#threading.Barrier" title="Link to this definition">¶</a></dt>
  1152. <dd><p>Create a barrier object for <em>parties</em> number of threads. An <em>action</em>, when
  1153. provided, is a callable to be called by one of the threads when they are
  1154. released. <em>timeout</em> is the default timeout value if none is specified for
  1155. the <a class="reference internal" href="#threading.Barrier.wait" title="threading.Barrier.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> method.</p>
  1156. <dl class="py method">
  1157. <dt class="sig sig-object py" id="threading.Barrier.wait">
  1158. <span class="sig-name descname"><span class="pre">wait</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#threading.Barrier.wait" title="Link to this definition">¶</a></dt>
  1159. <dd><p>Pass the barrier. When all the threads party to the barrier have called
  1160. this function, they are all released simultaneously. If a <em>timeout</em> is
  1161. provided, it is used in preference to any that was supplied to the class
  1162. constructor.</p>
  1163. <p>The return value is an integer in the range 0 to <em>parties</em> – 1, different
  1164. for each thread. This can be used to select a thread to do some special
  1165. housekeeping, e.g.:</p>
  1166. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">i</span> <span class="o">=</span> <span class="n">barrier</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>
  1167. <span class="k">if</span> <span class="n">i</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
  1168. <span class="c1"># Only one thread needs to print this</span>
  1169. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;passed the barrier&quot;</span><span class="p">)</span>
  1170. </pre></div>
  1171. </div>
  1172. <p>If an <em>action</em> was provided to the constructor, one of the threads will
  1173. have called it prior to being released. Should this call raise an error,
  1174. the barrier is put into the broken state.</p>
  1175. <p>If the call times out, the barrier is put into the broken state.</p>
  1176. <p>This method may raise a <a class="reference internal" href="#threading.BrokenBarrierError" title="threading.BrokenBarrierError"><code class="xref py py-class docutils literal notranslate"><span class="pre">BrokenBarrierError</span></code></a> exception if the
  1177. barrier is broken or reset while a thread is waiting.</p>
  1178. </dd></dl>
  1179. <dl class="py method">
  1180. <dt class="sig sig-object py" id="threading.Barrier.reset">
  1181. <span class="sig-name descname"><span class="pre">reset</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Barrier.reset" title="Link to this definition">¶</a></dt>
  1182. <dd><p>Return the barrier to the default, empty state. Any threads waiting on it
  1183. will receive the <a class="reference internal" href="#threading.BrokenBarrierError" title="threading.BrokenBarrierError"><code class="xref py py-class docutils literal notranslate"><span class="pre">BrokenBarrierError</span></code></a> exception.</p>
  1184. <p>Note that using this function may require some external
  1185. synchronization if there are other threads whose state is unknown. If a
  1186. barrier is broken it may be better to just leave it and create a new one.</p>
  1187. </dd></dl>
  1188. <dl class="py method">
  1189. <dt class="sig sig-object py" id="threading.Barrier.abort">
  1190. <span class="sig-name descname"><span class="pre">abort</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Barrier.abort" title="Link to this definition">¶</a></dt>
  1191. <dd><p>Put the barrier into a broken state. This causes any active or future
  1192. calls to <a class="reference internal" href="#threading.Barrier.wait" title="threading.Barrier.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> to fail with the <a class="reference internal" href="#threading.BrokenBarrierError" title="threading.BrokenBarrierError"><code class="xref py py-class docutils literal notranslate"><span class="pre">BrokenBarrierError</span></code></a>. Use
  1193. this for example if one of the threads needs to abort, to avoid deadlocking the
  1194. application.</p>
  1195. <p>It may be preferable to simply create the barrier with a sensible
  1196. <em>timeout</em> value to automatically guard against one of the threads going
  1197. awry.</p>
  1198. </dd></dl>
  1199. <dl class="py attribute">
  1200. <dt class="sig sig-object py" id="threading.Barrier.parties">
  1201. <span class="sig-name descname"><span class="pre">parties</span></span><a class="headerlink" href="#threading.Barrier.parties" title="Link to this definition">¶</a></dt>
  1202. <dd><p>The number of threads required to pass the barrier.</p>
  1203. </dd></dl>
  1204. <dl class="py attribute">
  1205. <dt class="sig sig-object py" id="threading.Barrier.n_waiting">
  1206. <span class="sig-name descname"><span class="pre">n_waiting</span></span><a class="headerlink" href="#threading.Barrier.n_waiting" title="Link to this definition">¶</a></dt>
  1207. <dd><p>The number of threads currently waiting in the barrier.</p>
  1208. </dd></dl>
  1209. <dl class="py attribute">
  1210. <dt class="sig sig-object py" id="threading.Barrier.broken">
  1211. <span class="sig-name descname"><span class="pre">broken</span></span><a class="headerlink" href="#threading.Barrier.broken" title="Link to this definition">¶</a></dt>
  1212. <dd><p>A boolean that is <code class="docutils literal notranslate"><span class="pre">True</span></code> if the barrier is in the broken state.</p>
  1213. </dd></dl>
  1214. </dd></dl>
  1215. <dl class="py exception">
  1216. <dt class="sig sig-object py" id="threading.BrokenBarrierError">
  1217. <em class="property"><span class="pre">exception</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">threading.</span></span><span class="sig-name descname"><span class="pre">BrokenBarrierError</span></span><a class="headerlink" href="#threading.BrokenBarrierError" title="Link to this definition">¶</a></dt>
  1218. <dd><p>This exception, a subclass of <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>, is raised when the
  1219. <a class="reference internal" href="#threading.Barrier" title="threading.Barrier"><code class="xref py py-class docutils literal notranslate"><span class="pre">Barrier</span></code></a> object is reset or broken.</p>
  1220. </dd></dl>
  1221. </section>
  1222. <section id="using-locks-conditions-and-semaphores-in-the-with-statement">
  1223. <span id="with-locks"></span><h2>Using locks, conditions, and semaphores in the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> statement<a class="headerlink" href="#using-locks-conditions-and-semaphores-in-the-with-statement" title="Link to this heading">¶</a></h2>
  1224. <p>All of the objects provided by this module that have <code class="docutils literal notranslate"><span class="pre">acquire</span></code> and
  1225. <code class="docutils literal notranslate"><span class="pre">release</span></code> methods can be used as context managers for a <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>
  1226. statement. The <code class="docutils literal notranslate"><span class="pre">acquire</span></code> method will be called when the block is
  1227. entered, and <code class="docutils literal notranslate"><span class="pre">release</span></code> will be called when the block is exited. Hence,
  1228. the following snippet:</p>
  1229. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">some_lock</span><span class="p">:</span>
  1230. <span class="c1"># do something...</span>
  1231. </pre></div>
  1232. </div>
  1233. <p>is equivalent to:</p>
  1234. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">some_lock</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>
  1235. <span class="k">try</span><span class="p">:</span>
  1236. <span class="c1"># do something...</span>
  1237. <span class="k">finally</span><span class="p">:</span>
  1238. <span class="n">some_lock</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>
  1239. </pre></div>
  1240. </div>
  1241. <p>Currently, <a class="reference internal" href="#threading.Lock" title="threading.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Lock</span></code></a>, <a class="reference internal" href="#threading.RLock" title="threading.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">RLock</span></code></a>, <a class="reference internal" href="#threading.Condition" title="threading.Condition"><code class="xref py py-class docutils literal notranslate"><span class="pre">Condition</span></code></a>,
  1242. <a class="reference internal" href="#threading.Semaphore" title="threading.Semaphore"><code class="xref py py-class docutils literal notranslate"><span class="pre">Semaphore</span></code></a>, and <a class="reference internal" href="#threading.BoundedSemaphore" title="threading.BoundedSemaphore"><code class="xref py py-class docutils literal notranslate"><span class="pre">BoundedSemaphore</span></code></a> objects may be used as
  1243. <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement context managers.</p>
  1244. </section>
  1245. </section>
  1246. <div class="clearer"></div>
  1247. </div>
  1248. </div>
  1249. </div>
  1250. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  1251. <div class="sphinxsidebarwrapper">
  1252. <div>
  1253. <h3><a href="../contents.html">Table of Contents</a></h3>
  1254. <ul>
  1255. <li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code> — Thread-based parallelism</a><ul>
  1256. <li><a class="reference internal" href="#thread-local-data">Thread-Local Data</a></li>
  1257. <li><a class="reference internal" href="#thread-objects">Thread Objects</a></li>
  1258. <li><a class="reference internal" href="#lock-objects">Lock Objects</a></li>
  1259. <li><a class="reference internal" href="#rlock-objects">RLock Objects</a></li>
  1260. <li><a class="reference internal" href="#condition-objects">Condition Objects</a></li>
  1261. <li><a class="reference internal" href="#semaphore-objects">Semaphore Objects</a><ul>
  1262. <li><a class="reference internal" href="#semaphore-example"><code class="xref py py-class docutils literal notranslate"><span class="pre">Semaphore</span></code> Example</a></li>
  1263. </ul>
  1264. </li>
  1265. <li><a class="reference internal" href="#event-objects">Event Objects</a></li>
  1266. <li><a class="reference internal" href="#timer-objects">Timer Objects</a></li>
  1267. <li><a class="reference internal" href="#barrier-objects">Barrier Objects</a></li>
  1268. <li><a class="reference internal" href="#using-locks-conditions-and-semaphores-in-the-with-statement">Using locks, conditions, and semaphores in the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> statement</a></li>
  1269. </ul>
  1270. </li>
  1271. </ul>
  1272. </div>
  1273. <div>
  1274. <h4>Previous topic</h4>
  1275. <p class="topless"><a href="concurrency.html"
  1276. title="previous chapter">Concurrent Execution</a></p>
  1277. </div>
  1278. <div>
  1279. <h4>Next topic</h4>
  1280. <p class="topless"><a href="multiprocessing.html"
  1281. title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code> — Process-based parallelism</a></p>
  1282. </div>
  1283. <div role="note" aria-label="source link">
  1284. <h3>This Page</h3>
  1285. <ul class="this-page-menu">
  1286. <li><a href="../bugs.html">Report a Bug</a></li>
  1287. <li>
  1288. <a href="https://github.com/python/cpython/blob/main/Doc/library/threading.rst"
  1289. rel="nofollow">Show Source
  1290. </a>
  1291. </li>
  1292. </ul>
  1293. </div>
  1294. </div>
  1295. <div id="sidebarbutton" title="Collapse sidebar">
  1296. <span>«</span>
  1297. </div>
  1298. </div>
  1299. <div class="clearer"></div>
  1300. </div>
  1301. <div class="related" role="navigation" aria-label="related navigation">
  1302. <h3>Navigation</h3>
  1303. <ul>
  1304. <li class="right" style="margin-right: 10px">
  1305. <a href="../genindex.html" title="General Index"
  1306. >index</a></li>
  1307. <li class="right" >
  1308. <a href="../py-modindex.html" title="Python Module Index"
  1309. >modules</a> |</li>
  1310. <li class="right" >
  1311. <a href="multiprocessing.html" title="multiprocessing — Process-based parallelism"
  1312. >next</a> |</li>
  1313. <li class="right" >
  1314. <a href="concurrency.html" title="Concurrent Execution"
  1315. >previous</a> |</li>
  1316. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  1317. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  1318. <li class="switchers">
  1319. <div class="language_switcher_placeholder"></div>
  1320. <div class="version_switcher_placeholder"></div>
  1321. </li>
  1322. <li>
  1323. </li>
  1324. <li id="cpython-language-and-version">
  1325. <a href="../index.html">3.12.3 Documentation</a> &#187;
  1326. </li>
  1327. <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
  1328. <li class="nav-item nav-item-2"><a href="concurrency.html" >Concurrent Execution</a> &#187;</li>
  1329. <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code> — Thread-based parallelism</a></li>
  1330. <li class="right">
  1331. <div class="inline-search" role="search">
  1332. <form class="inline-search" action="../search.html" method="get">
  1333. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  1334. <input type="submit" value="Go" />
  1335. </form>
  1336. </div>
  1337. |
  1338. </li>
  1339. <li class="right">
  1340. <label class="theme-selector-label">
  1341. Theme
  1342. <select class="theme-selector" oninput="activateTheme(this.value)">
  1343. <option value="auto" selected>Auto</option>
  1344. <option value="light">Light</option>
  1345. <option value="dark">Dark</option>
  1346. </select>
  1347. </label> |</li>
  1348. </ul>
  1349. </div>
  1350. <div class="footer">
  1351. &copy;
  1352. <a href="../copyright.html">
  1353. Copyright
  1354. </a>
  1355. 2001-2024, Python Software Foundation.
  1356. <br />
  1357. This page is licensed under the Python Software Foundation License Version 2.
  1358. <br />
  1359. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  1360. <br />
  1361. See <a href="/license.html">History and License</a> for more information.<br />
  1362. <br />
  1363. The Python Software Foundation is a non-profit corporation.
  1364. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  1365. <br />
  1366. <br />
  1367. Last updated on Apr 09, 2024 (13:47 UTC).
  1368. <a href="/bugs.html">Found a bug</a>?
  1369. <br />
  1370. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 7.2.6.
  1371. </div>
  1372. </body>
  1373. </html>
上海开阖软件有限公司 沪ICP备12045867号-1