17db96d56Sopenharmony_ci:mod:`threading` --- Thread-based parallelism
27db96d56Sopenharmony_ci=============================================
37db96d56Sopenharmony_ci
47db96d56Sopenharmony_ci.. module:: threading
57db96d56Sopenharmony_ci   :synopsis: Thread-based parallelism.
67db96d56Sopenharmony_ci
77db96d56Sopenharmony_ci**Source code:** :source:`Lib/threading.py`
87db96d56Sopenharmony_ci
97db96d56Sopenharmony_ci--------------
107db96d56Sopenharmony_ci
117db96d56Sopenharmony_ciThis module constructs higher-level threading interfaces on top of the lower
127db96d56Sopenharmony_cilevel :mod:`_thread` module.
137db96d56Sopenharmony_ci
147db96d56Sopenharmony_ci.. versionchanged:: 3.7
157db96d56Sopenharmony_ci   This module used to be optional, it is now always available.
167db96d56Sopenharmony_ci
177db96d56Sopenharmony_ci.. seealso::
187db96d56Sopenharmony_ci
197db96d56Sopenharmony_ci   :class:`concurrent.futures.ThreadPoolExecutor` offers a higher level interface
207db96d56Sopenharmony_ci   to push tasks to a background thread without blocking execution of the
217db96d56Sopenharmony_ci   calling thread, while still being able to retrieve their results when needed.
227db96d56Sopenharmony_ci
237db96d56Sopenharmony_ci   :mod:`queue` provides a thread-safe interface for exchanging data between
247db96d56Sopenharmony_ci   running threads.
257db96d56Sopenharmony_ci
267db96d56Sopenharmony_ci   :mod:`asyncio` offers an alternative approach to achieving task level
277db96d56Sopenharmony_ci   concurrency without requiring the use of multiple operating system threads.
287db96d56Sopenharmony_ci
297db96d56Sopenharmony_ci.. note::
307db96d56Sopenharmony_ci
317db96d56Sopenharmony_ci   In the Python 2.x series, this module contained ``camelCase`` names
327db96d56Sopenharmony_ci   for some methods and functions. These are deprecated as of Python 3.10,
337db96d56Sopenharmony_ci   but they are still supported for compatibility with Python 2.5 and lower.
347db96d56Sopenharmony_ci
357db96d56Sopenharmony_ci
367db96d56Sopenharmony_ci.. impl-detail::
377db96d56Sopenharmony_ci
387db96d56Sopenharmony_ci   In CPython, due to the :term:`Global Interpreter Lock
397db96d56Sopenharmony_ci   <global interpreter lock>`, only one thread
407db96d56Sopenharmony_ci   can execute Python code at once (even though certain performance-oriented
417db96d56Sopenharmony_ci   libraries might overcome this limitation).
427db96d56Sopenharmony_ci   If you want your application to make better use of the computational
437db96d56Sopenharmony_ci   resources of multi-core machines, you are advised to use
447db96d56Sopenharmony_ci   :mod:`multiprocessing` or :class:`concurrent.futures.ProcessPoolExecutor`.
457db96d56Sopenharmony_ci   However, threading is still an appropriate model if you want to run
467db96d56Sopenharmony_ci   multiple I/O-bound tasks simultaneously.
477db96d56Sopenharmony_ci
487db96d56Sopenharmony_ci.. include:: ../includes/wasm-notavail.rst
497db96d56Sopenharmony_ci
507db96d56Sopenharmony_ciThis module defines the following functions:
517db96d56Sopenharmony_ci
527db96d56Sopenharmony_ci
537db96d56Sopenharmony_ci.. function:: active_count()
547db96d56Sopenharmony_ci
557db96d56Sopenharmony_ci   Return the number of :class:`Thread` objects currently alive.  The returned
567db96d56Sopenharmony_ci   count is equal to the length of the list returned by :func:`.enumerate`.
577db96d56Sopenharmony_ci
587db96d56Sopenharmony_ci   The function ``activeCount`` is a deprecated alias for this function.
597db96d56Sopenharmony_ci
607db96d56Sopenharmony_ci
617db96d56Sopenharmony_ci.. function:: current_thread()
627db96d56Sopenharmony_ci
637db96d56Sopenharmony_ci   Return the current :class:`Thread` object, corresponding to the caller's thread
647db96d56Sopenharmony_ci   of control.  If the caller's thread of control was not created through the
657db96d56Sopenharmony_ci   :mod:`threading` module, a dummy thread object with limited functionality is
667db96d56Sopenharmony_ci   returned.
677db96d56Sopenharmony_ci
687db96d56Sopenharmony_ci   The function ``currentThread`` is a deprecated alias for this function.
697db96d56Sopenharmony_ci
707db96d56Sopenharmony_ci
717db96d56Sopenharmony_ci.. function:: excepthook(args, /)
727db96d56Sopenharmony_ci
737db96d56Sopenharmony_ci   Handle uncaught exception raised by :func:`Thread.run`.
747db96d56Sopenharmony_ci
757db96d56Sopenharmony_ci   The *args* argument has the following attributes:
767db96d56Sopenharmony_ci
777db96d56Sopenharmony_ci   * *exc_type*: Exception type.
787db96d56Sopenharmony_ci   * *exc_value*: Exception value, can be ``None``.
797db96d56Sopenharmony_ci   * *exc_traceback*: Exception traceback, can be ``None``.
807db96d56Sopenharmony_ci   * *thread*: Thread which raised the exception, can be ``None``.
817db96d56Sopenharmony_ci
827db96d56Sopenharmony_ci   If *exc_type* is :exc:`SystemExit`, the exception is silently ignored.
837db96d56Sopenharmony_ci   Otherwise, the exception is printed out on :data:`sys.stderr`.
847db96d56Sopenharmony_ci
857db96d56Sopenharmony_ci   If  this function raises an exception, :func:`sys.excepthook` is called to
867db96d56Sopenharmony_ci   handle it.
877db96d56Sopenharmony_ci
887db96d56Sopenharmony_ci   :func:`threading.excepthook` can be overridden to control how uncaught
897db96d56Sopenharmony_ci   exceptions raised by :func:`Thread.run` are handled.
907db96d56Sopenharmony_ci
917db96d56Sopenharmony_ci   Storing *exc_value* using a custom hook can create a reference cycle. It
927db96d56Sopenharmony_ci   should be cleared explicitly to break the reference cycle when the
937db96d56Sopenharmony_ci   exception is no longer needed.
947db96d56Sopenharmony_ci
957db96d56Sopenharmony_ci   Storing *thread* using a custom hook can resurrect it if it is set to an
967db96d56Sopenharmony_ci   object which is being finalized. Avoid storing *thread* after the custom
977db96d56Sopenharmony_ci   hook completes to avoid resurrecting objects.
987db96d56Sopenharmony_ci
997db96d56Sopenharmony_ci   .. seealso::
1007db96d56Sopenharmony_ci      :func:`sys.excepthook` handles uncaught exceptions.
1017db96d56Sopenharmony_ci
1027db96d56Sopenharmony_ci   .. versionadded:: 3.8
1037db96d56Sopenharmony_ci
1047db96d56Sopenharmony_ci.. data:: __excepthook__
1057db96d56Sopenharmony_ci
1067db96d56Sopenharmony_ci   Holds the original value of :func:`threading.excepthook`. It is saved so that the
1077db96d56Sopenharmony_ci   original value can be restored in case they happen to get replaced with
1087db96d56Sopenharmony_ci   broken or alternative objects.
1097db96d56Sopenharmony_ci
1107db96d56Sopenharmony_ci   .. versionadded:: 3.10
1117db96d56Sopenharmony_ci
1127db96d56Sopenharmony_ci.. function:: get_ident()
1137db96d56Sopenharmony_ci
1147db96d56Sopenharmony_ci   Return the 'thread identifier' of the current thread.  This is a nonzero
1157db96d56Sopenharmony_ci   integer.  Its value has no direct meaning; it is intended as a magic cookie
1167db96d56Sopenharmony_ci   to be used e.g. to index a dictionary of thread-specific data.  Thread
1177db96d56Sopenharmony_ci   identifiers may be recycled when a thread exits and another thread is
1187db96d56Sopenharmony_ci   created.
1197db96d56Sopenharmony_ci
1207db96d56Sopenharmony_ci   .. versionadded:: 3.3
1217db96d56Sopenharmony_ci
1227db96d56Sopenharmony_ci
1237db96d56Sopenharmony_ci.. function:: get_native_id()
1247db96d56Sopenharmony_ci
1257db96d56Sopenharmony_ci   Return the native integral Thread ID of the current thread assigned by the kernel.
1267db96d56Sopenharmony_ci   This is a non-negative integer.
1277db96d56Sopenharmony_ci   Its value may be used to uniquely identify this particular thread system-wide
1287db96d56Sopenharmony_ci   (until the thread terminates, after which the value may be recycled by the OS).
1297db96d56Sopenharmony_ci
1307db96d56Sopenharmony_ci   .. availability:: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX.
1317db96d56Sopenharmony_ci
1327db96d56Sopenharmony_ci   .. versionadded:: 3.8
1337db96d56Sopenharmony_ci
1347db96d56Sopenharmony_ci
1357db96d56Sopenharmony_ci.. function:: enumerate()
1367db96d56Sopenharmony_ci
1377db96d56Sopenharmony_ci   Return a list of all :class:`Thread` objects currently active.  The list
1387db96d56Sopenharmony_ci   includes daemonic threads and dummy thread objects created by
1397db96d56Sopenharmony_ci   :func:`current_thread`.  It excludes terminated threads and threads
1407db96d56Sopenharmony_ci   that have not yet been started.  However, the main thread is always part
1417db96d56Sopenharmony_ci   of the result, even when terminated.
1427db96d56Sopenharmony_ci
1437db96d56Sopenharmony_ci
1447db96d56Sopenharmony_ci.. function:: main_thread()
1457db96d56Sopenharmony_ci
1467db96d56Sopenharmony_ci   Return the main :class:`Thread` object.  In normal conditions, the
1477db96d56Sopenharmony_ci   main thread is the thread from which the Python interpreter was
1487db96d56Sopenharmony_ci   started.
1497db96d56Sopenharmony_ci
1507db96d56Sopenharmony_ci   .. versionadded:: 3.4
1517db96d56Sopenharmony_ci
1527db96d56Sopenharmony_ci
1537db96d56Sopenharmony_ci.. function:: settrace(func)
1547db96d56Sopenharmony_ci
1557db96d56Sopenharmony_ci   .. index:: single: trace function
1567db96d56Sopenharmony_ci
1577db96d56Sopenharmony_ci   Set a trace function for all threads started from the :mod:`threading` module.
1587db96d56Sopenharmony_ci   The *func* will be passed to  :func:`sys.settrace` for each thread, before its
1597db96d56Sopenharmony_ci   :meth:`~Thread.run` method is called.
1607db96d56Sopenharmony_ci
1617db96d56Sopenharmony_ci
1627db96d56Sopenharmony_ci.. function:: gettrace()
1637db96d56Sopenharmony_ci
1647db96d56Sopenharmony_ci   .. index::
1657db96d56Sopenharmony_ci      single: trace function
1667db96d56Sopenharmony_ci      single: debugger
1677db96d56Sopenharmony_ci
1687db96d56Sopenharmony_ci   Get the trace function as set by :func:`settrace`.
1697db96d56Sopenharmony_ci
1707db96d56Sopenharmony_ci   .. versionadded:: 3.10
1717db96d56Sopenharmony_ci
1727db96d56Sopenharmony_ci
1737db96d56Sopenharmony_ci.. function:: setprofile(func)
1747db96d56Sopenharmony_ci
1757db96d56Sopenharmony_ci   .. index:: single: profile function
1767db96d56Sopenharmony_ci
1777db96d56Sopenharmony_ci   Set a profile function for all threads started from the :mod:`threading` module.
1787db96d56Sopenharmony_ci   The *func* will be passed to  :func:`sys.setprofile` for each thread, before its
1797db96d56Sopenharmony_ci   :meth:`~Thread.run` method is called.
1807db96d56Sopenharmony_ci
1817db96d56Sopenharmony_ci
1827db96d56Sopenharmony_ci.. function:: getprofile()
1837db96d56Sopenharmony_ci
1847db96d56Sopenharmony_ci   .. index:: single: profile function
1857db96d56Sopenharmony_ci
1867db96d56Sopenharmony_ci   Get the profiler function as set by :func:`setprofile`.
1877db96d56Sopenharmony_ci
1887db96d56Sopenharmony_ci   .. versionadded:: 3.10
1897db96d56Sopenharmony_ci
1907db96d56Sopenharmony_ci
1917db96d56Sopenharmony_ci.. function:: stack_size([size])
1927db96d56Sopenharmony_ci
1937db96d56Sopenharmony_ci   Return the thread stack size used when creating new threads.  The optional
1947db96d56Sopenharmony_ci   *size* argument specifies the stack size to be used for subsequently created
1957db96d56Sopenharmony_ci   threads, and must be 0 (use platform or configured default) or a positive
1967db96d56Sopenharmony_ci   integer value of at least 32,768 (32 KiB). If *size* is not specified,
1977db96d56Sopenharmony_ci   0 is used.  If changing the thread stack size is
1987db96d56Sopenharmony_ci   unsupported, a :exc:`RuntimeError` is raised.  If the specified stack size is
1997db96d56Sopenharmony_ci   invalid, a :exc:`ValueError` is raised and the stack size is unmodified.  32 KiB
2007db96d56Sopenharmony_ci   is currently the minimum supported stack size value to guarantee sufficient
2017db96d56Sopenharmony_ci   stack space for the interpreter itself.  Note that some platforms may have
2027db96d56Sopenharmony_ci   particular restrictions on values for the stack size, such as requiring a
2037db96d56Sopenharmony_ci   minimum stack size > 32 KiB or requiring allocation in multiples of the system
2047db96d56Sopenharmony_ci   memory page size - platform documentation should be referred to for more
2057db96d56Sopenharmony_ci   information (4 KiB pages are common; using multiples of 4096 for the stack size is
2067db96d56Sopenharmony_ci   the suggested approach in the absence of more specific information).
2077db96d56Sopenharmony_ci
2087db96d56Sopenharmony_ci   .. availability:: Windows, pthreads.
2097db96d56Sopenharmony_ci
2107db96d56Sopenharmony_ci      Unix platforms with POSIX threads support.
2117db96d56Sopenharmony_ci
2127db96d56Sopenharmony_ci
2137db96d56Sopenharmony_ciThis module also defines the following constant:
2147db96d56Sopenharmony_ci
2157db96d56Sopenharmony_ci.. data:: TIMEOUT_MAX
2167db96d56Sopenharmony_ci
2177db96d56Sopenharmony_ci   The maximum value allowed for the *timeout* parameter of blocking functions
2187db96d56Sopenharmony_ci   (:meth:`Lock.acquire`, :meth:`RLock.acquire`, :meth:`Condition.wait`, etc.).
2197db96d56Sopenharmony_ci   Specifying a timeout greater than this value will raise an
2207db96d56Sopenharmony_ci   :exc:`OverflowError`.
2217db96d56Sopenharmony_ci
2227db96d56Sopenharmony_ci   .. versionadded:: 3.2
2237db96d56Sopenharmony_ci
2247db96d56Sopenharmony_ci
2257db96d56Sopenharmony_ciThis module defines a number of classes, which are detailed in the sections
2267db96d56Sopenharmony_cibelow.
2277db96d56Sopenharmony_ci
2287db96d56Sopenharmony_ciThe design of this module is loosely based on Java's threading model. However,
2297db96d56Sopenharmony_ciwhere Java makes locks and condition variables basic behavior of every object,
2307db96d56Sopenharmony_cithey are separate objects in Python.  Python's :class:`Thread` class supports a
2317db96d56Sopenharmony_cisubset of the behavior of Java's Thread class; currently, there are no
2327db96d56Sopenharmony_cipriorities, no thread groups, and threads cannot be destroyed, stopped,
2337db96d56Sopenharmony_cisuspended, resumed, or interrupted.  The static methods of Java's Thread class,
2347db96d56Sopenharmony_ciwhen implemented, are mapped to module-level functions.
2357db96d56Sopenharmony_ci
2367db96d56Sopenharmony_ciAll of the methods described below are executed atomically.
2377db96d56Sopenharmony_ci
2387db96d56Sopenharmony_ci
2397db96d56Sopenharmony_ciThread-Local Data
2407db96d56Sopenharmony_ci-----------------
2417db96d56Sopenharmony_ci
2427db96d56Sopenharmony_ciThread-local data is data whose values are thread specific.  To manage
2437db96d56Sopenharmony_cithread-local data, just create an instance of :class:`local` (or a
2447db96d56Sopenharmony_cisubclass) and store attributes on it::
2457db96d56Sopenharmony_ci
2467db96d56Sopenharmony_ci  mydata = threading.local()
2477db96d56Sopenharmony_ci  mydata.x = 1
2487db96d56Sopenharmony_ci
2497db96d56Sopenharmony_ciThe instance's values will be different for separate threads.
2507db96d56Sopenharmony_ci
2517db96d56Sopenharmony_ci
2527db96d56Sopenharmony_ci.. class:: local()
2537db96d56Sopenharmony_ci
2547db96d56Sopenharmony_ci   A class that represents thread-local data.
2557db96d56Sopenharmony_ci
2567db96d56Sopenharmony_ci   For more details and extensive examples, see the documentation string of the
2577db96d56Sopenharmony_ci   :mod:`_threading_local` module: :source:`Lib/_threading_local.py`.
2587db96d56Sopenharmony_ci
2597db96d56Sopenharmony_ci
2607db96d56Sopenharmony_ci.. _thread-objects:
2617db96d56Sopenharmony_ci
2627db96d56Sopenharmony_ciThread Objects
2637db96d56Sopenharmony_ci--------------
2647db96d56Sopenharmony_ci
2657db96d56Sopenharmony_ciThe :class:`Thread` class represents an activity that is run in a separate
2667db96d56Sopenharmony_cithread of control.  There are two ways to specify the activity: by passing a
2677db96d56Sopenharmony_cicallable object to the constructor, or by overriding the :meth:`~Thread.run`
2687db96d56Sopenharmony_cimethod in a subclass.  No other methods (except for the constructor) should be
2697db96d56Sopenharmony_cioverridden in a subclass.  In other words, *only*  override the
2707db96d56Sopenharmony_ci:meth:`~Thread.__init__` and :meth:`~Thread.run` methods of this class.
2717db96d56Sopenharmony_ci
2727db96d56Sopenharmony_ciOnce a thread object is created, its activity must be started by calling the
2737db96d56Sopenharmony_cithread's :meth:`~Thread.start` method.  This invokes the :meth:`~Thread.run`
2747db96d56Sopenharmony_cimethod in a separate thread of control.
2757db96d56Sopenharmony_ci
2767db96d56Sopenharmony_ciOnce the thread's activity is started, the thread is considered 'alive'. It
2777db96d56Sopenharmony_cistops being alive when its :meth:`~Thread.run` method terminates -- either
2787db96d56Sopenharmony_cinormally, or by raising an unhandled exception.  The :meth:`~Thread.is_alive`
2797db96d56Sopenharmony_cimethod tests whether the thread is alive.
2807db96d56Sopenharmony_ci
2817db96d56Sopenharmony_ciOther threads can call a thread's :meth:`~Thread.join` method.  This blocks
2827db96d56Sopenharmony_cithe calling thread until the thread whose :meth:`~Thread.join` method is
2837db96d56Sopenharmony_cicalled is terminated.
2847db96d56Sopenharmony_ci
2857db96d56Sopenharmony_ciA thread has a name.  The name can be passed to the constructor, and read or
2867db96d56Sopenharmony_cichanged through the :attr:`~Thread.name` attribute.
2877db96d56Sopenharmony_ci
2887db96d56Sopenharmony_ciIf the :meth:`~Thread.run` method raises an exception,
2897db96d56Sopenharmony_ci:func:`threading.excepthook` is called to handle it. By default,
2907db96d56Sopenharmony_ci:func:`threading.excepthook` ignores silently :exc:`SystemExit`.
2917db96d56Sopenharmony_ci
2927db96d56Sopenharmony_ciA thread can be flagged as a "daemon thread".  The significance of this flag is
2937db96d56Sopenharmony_cithat the entire Python program exits when only daemon threads are left.  The
2947db96d56Sopenharmony_ciinitial value is inherited from the creating thread.  The flag can be set
2957db96d56Sopenharmony_cithrough the :attr:`~Thread.daemon` property or the *daemon* constructor
2967db96d56Sopenharmony_ciargument.
2977db96d56Sopenharmony_ci
2987db96d56Sopenharmony_ci.. note::
2997db96d56Sopenharmony_ci   Daemon threads are abruptly stopped at shutdown.  Their resources (such
3007db96d56Sopenharmony_ci   as open files, database transactions, etc.) may not be released properly.
3017db96d56Sopenharmony_ci   If you want your threads to stop gracefully, make them non-daemonic and
3027db96d56Sopenharmony_ci   use a suitable signalling mechanism such as an :class:`Event`.
3037db96d56Sopenharmony_ci
3047db96d56Sopenharmony_ciThere is a "main thread" object; this corresponds to the initial thread of
3057db96d56Sopenharmony_cicontrol in the Python program.  It is not a daemon thread.
3067db96d56Sopenharmony_ci
3077db96d56Sopenharmony_ciThere is the possibility that "dummy thread objects" are created. These are
3087db96d56Sopenharmony_cithread objects corresponding to "alien threads", which are threads of control
3097db96d56Sopenharmony_cistarted outside the threading module, such as directly from C code.  Dummy
3107db96d56Sopenharmony_cithread objects have limited functionality; they are always considered alive and
3117db96d56Sopenharmony_cidaemonic, and cannot be :ref:`joined <meth-thread-join>`.  They are never deleted,
3127db96d56Sopenharmony_cisince it is impossible to detect the termination of alien threads.
3137db96d56Sopenharmony_ci
3147db96d56Sopenharmony_ci
3157db96d56Sopenharmony_ci.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={}, *, \
3167db96d56Sopenharmony_ci                  daemon=None)
3177db96d56Sopenharmony_ci
3187db96d56Sopenharmony_ci   This constructor should always be called with keyword arguments.  Arguments
3197db96d56Sopenharmony_ci   are:
3207db96d56Sopenharmony_ci
3217db96d56Sopenharmony_ci   *group* should be ``None``; reserved for future extension when a
3227db96d56Sopenharmony_ci   :class:`ThreadGroup` class is implemented.
3237db96d56Sopenharmony_ci
3247db96d56Sopenharmony_ci   *target* is the callable object to be invoked by the :meth:`run` method.
3257db96d56Sopenharmony_ci   Defaults to ``None``, meaning nothing is called.
3267db96d56Sopenharmony_ci
3277db96d56Sopenharmony_ci   *name* is the thread name. By default, a unique name is constructed
3287db96d56Sopenharmony_ci   of the form "Thread-*N*" where *N* is a small decimal number,
3297db96d56Sopenharmony_ci   or "Thread-*N* (target)" where "target" is ``target.__name__`` if the
3307db96d56Sopenharmony_ci   *target* argument is specified.
3317db96d56Sopenharmony_ci
3327db96d56Sopenharmony_ci   *args* is a list or tuple of arguments for the target invocation.  Defaults to ``()``.
3337db96d56Sopenharmony_ci
3347db96d56Sopenharmony_ci   *kwargs* is a dictionary of keyword arguments for the target invocation.
3357db96d56Sopenharmony_ci   Defaults to ``{}``.
3367db96d56Sopenharmony_ci
3377db96d56Sopenharmony_ci   If not ``None``, *daemon* explicitly sets whether the thread is daemonic.
3387db96d56Sopenharmony_ci   If ``None`` (the default), the daemonic property is inherited from the
3397db96d56Sopenharmony_ci   current thread.
3407db96d56Sopenharmony_ci
3417db96d56Sopenharmony_ci   If the subclass overrides the constructor, it must make sure to invoke the
3427db96d56Sopenharmony_ci   base class constructor (``Thread.__init__()``) before doing anything else to
3437db96d56Sopenharmony_ci   the thread.
3447db96d56Sopenharmony_ci
3457db96d56Sopenharmony_ci   .. versionchanged:: 3.10
3467db96d56Sopenharmony_ci      Use the *target* name if *name* argument is omitted.
3477db96d56Sopenharmony_ci
3487db96d56Sopenharmony_ci   .. versionchanged:: 3.3
3497db96d56Sopenharmony_ci      Added the *daemon* argument.
3507db96d56Sopenharmony_ci
3517db96d56Sopenharmony_ci   .. method:: start()
3527db96d56Sopenharmony_ci
3537db96d56Sopenharmony_ci      Start the thread's activity.
3547db96d56Sopenharmony_ci
3557db96d56Sopenharmony_ci      It must be called at most once per thread object.  It arranges for the
3567db96d56Sopenharmony_ci      object's :meth:`~Thread.run` method to be invoked in a separate thread
3577db96d56Sopenharmony_ci      of control.
3587db96d56Sopenharmony_ci
3597db96d56Sopenharmony_ci      This method will raise a :exc:`RuntimeError` if called more than once
3607db96d56Sopenharmony_ci      on the same thread object.
3617db96d56Sopenharmony_ci
3627db96d56Sopenharmony_ci   .. method:: run()
3637db96d56Sopenharmony_ci
3647db96d56Sopenharmony_ci      Method representing the thread's activity.
3657db96d56Sopenharmony_ci
3667db96d56Sopenharmony_ci      You may override this method in a subclass.  The standard :meth:`run`
3677db96d56Sopenharmony_ci      method invokes the callable object passed to the object's constructor as
3687db96d56Sopenharmony_ci      the *target* argument, if any, with positional and keyword arguments taken
3697db96d56Sopenharmony_ci      from the *args* and *kwargs* arguments, respectively.
3707db96d56Sopenharmony_ci
3717db96d56Sopenharmony_ci      Using list or tuple as the *args* argument which passed to the :class:`Thread`
3727db96d56Sopenharmony_ci      could achieve the same effect.
3737db96d56Sopenharmony_ci
3747db96d56Sopenharmony_ci      Example::
3757db96d56Sopenharmony_ci
3767db96d56Sopenharmony_ci         >>> from threading import Thread
3777db96d56Sopenharmony_ci         >>> t = Thread(target=print, args=[1])
3787db96d56Sopenharmony_ci         >>> t.run()
3797db96d56Sopenharmony_ci         1
3807db96d56Sopenharmony_ci         >>> t = Thread(target=print, args=(1,))
3817db96d56Sopenharmony_ci         >>> t.run()
3827db96d56Sopenharmony_ci         1
3837db96d56Sopenharmony_ci
3847db96d56Sopenharmony_ci   .. _meth-thread-join:
3857db96d56Sopenharmony_ci
3867db96d56Sopenharmony_ci   .. method:: join(timeout=None)
3877db96d56Sopenharmony_ci
3887db96d56Sopenharmony_ci      Wait until the thread terminates. This blocks the calling thread until
3897db96d56Sopenharmony_ci      the thread whose :meth:`~Thread.join` method is called terminates -- either
3907db96d56Sopenharmony_ci      normally or through an unhandled exception -- or until the optional
3917db96d56Sopenharmony_ci      timeout occurs.
3927db96d56Sopenharmony_ci
3937db96d56Sopenharmony_ci      When the *timeout* argument is present and not ``None``, it should be a
3947db96d56Sopenharmony_ci      floating point number specifying a timeout for the operation in seconds
3957db96d56Sopenharmony_ci      (or fractions thereof). As :meth:`~Thread.join` always returns ``None``,
3967db96d56Sopenharmony_ci      you must call :meth:`~Thread.is_alive` after :meth:`~Thread.join` to
3977db96d56Sopenharmony_ci      decide whether a timeout happened -- if the thread is still alive, the
3987db96d56Sopenharmony_ci      :meth:`~Thread.join` call timed out.
3997db96d56Sopenharmony_ci
4007db96d56Sopenharmony_ci      When the *timeout* argument is not present or ``None``, the operation will
4017db96d56Sopenharmony_ci      block until the thread terminates.
4027db96d56Sopenharmony_ci
4037db96d56Sopenharmony_ci      A thread can be joined many times.
4047db96d56Sopenharmony_ci
4057db96d56Sopenharmony_ci      :meth:`~Thread.join` raises a :exc:`RuntimeError` if an attempt is made
4067db96d56Sopenharmony_ci      to join the current thread as that would cause a deadlock. It is also
4077db96d56Sopenharmony_ci      an error to :meth:`~Thread.join` a thread before it has been started
4087db96d56Sopenharmony_ci      and attempts to do so raise the same exception.
4097db96d56Sopenharmony_ci
4107db96d56Sopenharmony_ci   .. attribute:: name
4117db96d56Sopenharmony_ci
4127db96d56Sopenharmony_ci      A string used for identification purposes only. It has no semantics.
4137db96d56Sopenharmony_ci      Multiple threads may be given the same name.  The initial name is set by
4147db96d56Sopenharmony_ci      the constructor.
4157db96d56Sopenharmony_ci
4167db96d56Sopenharmony_ci   .. method:: getName()
4177db96d56Sopenharmony_ci               setName()
4187db96d56Sopenharmony_ci
4197db96d56Sopenharmony_ci      Deprecated getter/setter API for :attr:`~Thread.name`; use it directly as a
4207db96d56Sopenharmony_ci      property instead.
4217db96d56Sopenharmony_ci
4227db96d56Sopenharmony_ci      .. deprecated:: 3.10
4237db96d56Sopenharmony_ci
4247db96d56Sopenharmony_ci   .. attribute:: ident
4257db96d56Sopenharmony_ci
4267db96d56Sopenharmony_ci      The 'thread identifier' of this thread or ``None`` if the thread has not
4277db96d56Sopenharmony_ci      been started.  This is a nonzero integer.  See the :func:`get_ident`
4287db96d56Sopenharmony_ci      function.  Thread identifiers may be recycled when a thread exits and
4297db96d56Sopenharmony_ci      another thread is created.  The identifier is available even after the
4307db96d56Sopenharmony_ci      thread has exited.
4317db96d56Sopenharmony_ci
4327db96d56Sopenharmony_ci   .. attribute:: native_id
4337db96d56Sopenharmony_ci
4347db96d56Sopenharmony_ci      The Thread ID (``TID``) of this thread, as assigned by the OS (kernel).
4357db96d56Sopenharmony_ci      This is a non-negative integer, or ``None`` if the thread has not
4367db96d56Sopenharmony_ci      been started. See the :func:`get_native_id` function.
4377db96d56Sopenharmony_ci      This value may be used to uniquely identify this particular thread
4387db96d56Sopenharmony_ci      system-wide (until the thread terminates, after which the value
4397db96d56Sopenharmony_ci      may be recycled by the OS).
4407db96d56Sopenharmony_ci
4417db96d56Sopenharmony_ci      .. note::
4427db96d56Sopenharmony_ci
4437db96d56Sopenharmony_ci         Similar to Process IDs, Thread IDs are only valid (guaranteed unique
4447db96d56Sopenharmony_ci         system-wide) from the time the thread is created until the thread
4457db96d56Sopenharmony_ci         has been terminated.
4467db96d56Sopenharmony_ci
4477db96d56Sopenharmony_ci      .. availability:: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX, DragonFlyBSD.
4487db96d56Sopenharmony_ci
4497db96d56Sopenharmony_ci      .. versionadded:: 3.8
4507db96d56Sopenharmony_ci
4517db96d56Sopenharmony_ci   .. method:: is_alive()
4527db96d56Sopenharmony_ci
4537db96d56Sopenharmony_ci      Return whether the thread is alive.
4547db96d56Sopenharmony_ci
4557db96d56Sopenharmony_ci      This method returns ``True`` just before the :meth:`~Thread.run` method
4567db96d56Sopenharmony_ci      starts until just after the :meth:`~Thread.run` method terminates.  The
4577db96d56Sopenharmony_ci      module function :func:`.enumerate` returns a list of all alive threads.
4587db96d56Sopenharmony_ci
4597db96d56Sopenharmony_ci   .. attribute:: daemon
4607db96d56Sopenharmony_ci
4617db96d56Sopenharmony_ci      A boolean value indicating whether this thread is a daemon thread (``True``)
4627db96d56Sopenharmony_ci      or not (``False``).  This must be set before :meth:`~Thread.start` is called,
4637db96d56Sopenharmony_ci      otherwise :exc:`RuntimeError` is raised.  Its initial value is inherited
4647db96d56Sopenharmony_ci      from the creating thread; the main thread is not a daemon thread and
4657db96d56Sopenharmony_ci      therefore all threads created in the main thread default to
4667db96d56Sopenharmony_ci      :attr:`~Thread.daemon` = ``False``.
4677db96d56Sopenharmony_ci
4687db96d56Sopenharmony_ci      The entire Python program exits when no alive non-daemon threads are left.
4697db96d56Sopenharmony_ci
4707db96d56Sopenharmony_ci   .. method:: isDaemon()
4717db96d56Sopenharmony_ci               setDaemon()
4727db96d56Sopenharmony_ci
4737db96d56Sopenharmony_ci      Deprecated getter/setter API for :attr:`~Thread.daemon`; use it directly as a
4747db96d56Sopenharmony_ci      property instead.
4757db96d56Sopenharmony_ci
4767db96d56Sopenharmony_ci      .. deprecated:: 3.10
4777db96d56Sopenharmony_ci
4787db96d56Sopenharmony_ci
4797db96d56Sopenharmony_ci.. _lock-objects:
4807db96d56Sopenharmony_ci
4817db96d56Sopenharmony_ciLock Objects
4827db96d56Sopenharmony_ci------------
4837db96d56Sopenharmony_ci
4847db96d56Sopenharmony_ciA primitive lock is a synchronization primitive that is not owned by a
4857db96d56Sopenharmony_ciparticular thread when locked.  In Python, it is currently the lowest level
4867db96d56Sopenharmony_cisynchronization primitive available, implemented directly by the :mod:`_thread`
4877db96d56Sopenharmony_ciextension module.
4887db96d56Sopenharmony_ci
4897db96d56Sopenharmony_ciA primitive lock is in one of two states, "locked" or "unlocked". It is created
4907db96d56Sopenharmony_ciin the unlocked state.  It has two basic methods, :meth:`~Lock.acquire` and
4917db96d56Sopenharmony_ci:meth:`~Lock.release`.  When the state is unlocked, :meth:`~Lock.acquire`
4927db96d56Sopenharmony_cichanges the state to locked and returns immediately.  When the state is locked,
4937db96d56Sopenharmony_ci:meth:`~Lock.acquire` blocks until a call to :meth:`~Lock.release` in another
4947db96d56Sopenharmony_cithread changes it to unlocked, then the :meth:`~Lock.acquire` call resets it
4957db96d56Sopenharmony_cito locked and returns.  The :meth:`~Lock.release` method should only be
4967db96d56Sopenharmony_cicalled in the locked state; it changes the state to unlocked and returns
4977db96d56Sopenharmony_ciimmediately. If an attempt is made to release an unlocked lock, a
4987db96d56Sopenharmony_ci:exc:`RuntimeError` will be raised.
4997db96d56Sopenharmony_ci
5007db96d56Sopenharmony_ciLocks also support the :ref:`context management protocol <with-locks>`.
5017db96d56Sopenharmony_ci
5027db96d56Sopenharmony_ciWhen more than one thread is blocked in :meth:`~Lock.acquire` waiting for the
5037db96d56Sopenharmony_cistate to turn to unlocked, only one thread proceeds when a :meth:`~Lock.release`
5047db96d56Sopenharmony_cicall resets the state to unlocked; which one of the waiting threads proceeds
5057db96d56Sopenharmony_ciis not defined, and may vary across implementations.
5067db96d56Sopenharmony_ci
5077db96d56Sopenharmony_ciAll methods are executed atomically.
5087db96d56Sopenharmony_ci
5097db96d56Sopenharmony_ci
5107db96d56Sopenharmony_ci.. class:: Lock()
5117db96d56Sopenharmony_ci
5127db96d56Sopenharmony_ci   The class implementing primitive lock objects.  Once a thread has acquired a
5137db96d56Sopenharmony_ci   lock, subsequent attempts to acquire it block, until it is released; any
5147db96d56Sopenharmony_ci   thread may release it.
5157db96d56Sopenharmony_ci
5167db96d56Sopenharmony_ci   Note that ``Lock`` is actually a factory function which returns an instance
5177db96d56Sopenharmony_ci   of the most efficient version of the concrete Lock class that is supported
5187db96d56Sopenharmony_ci   by the platform.
5197db96d56Sopenharmony_ci
5207db96d56Sopenharmony_ci
5217db96d56Sopenharmony_ci   .. method:: acquire(blocking=True, timeout=-1)
5227db96d56Sopenharmony_ci
5237db96d56Sopenharmony_ci      Acquire a lock, blocking or non-blocking.
5247db96d56Sopenharmony_ci
5257db96d56Sopenharmony_ci      When invoked with the *blocking* argument set to ``True`` (the default),
5267db96d56Sopenharmony_ci      block until the lock is unlocked, then set it to locked and return ``True``.
5277db96d56Sopenharmony_ci
5287db96d56Sopenharmony_ci      When invoked with the *blocking* argument set to ``False``, do not block.
5297db96d56Sopenharmony_ci      If a call with *blocking* set to ``True`` would block, return ``False``
5307db96d56Sopenharmony_ci      immediately; otherwise, set the lock to locked and return ``True``.
5317db96d56Sopenharmony_ci
5327db96d56Sopenharmony_ci      When invoked with the floating-point *timeout* argument set to a positive
5337db96d56Sopenharmony_ci      value, block for at most the number of seconds specified by *timeout*
5347db96d56Sopenharmony_ci      and as long as the lock cannot be acquired.  A *timeout* argument of ``-1``
5357db96d56Sopenharmony_ci      specifies an unbounded wait.  It is forbidden to specify a *timeout*
5367db96d56Sopenharmony_ci      when *blocking* is ``False``.
5377db96d56Sopenharmony_ci
5387db96d56Sopenharmony_ci      The return value is ``True`` if the lock is acquired successfully,
5397db96d56Sopenharmony_ci      ``False`` if not (for example if the *timeout* expired).
5407db96d56Sopenharmony_ci
5417db96d56Sopenharmony_ci      .. versionchanged:: 3.2
5427db96d56Sopenharmony_ci         The *timeout* parameter is new.
5437db96d56Sopenharmony_ci
5447db96d56Sopenharmony_ci      .. versionchanged:: 3.2
5457db96d56Sopenharmony_ci         Lock acquisition can now be interrupted by signals on POSIX if the
5467db96d56Sopenharmony_ci         underlying threading implementation supports it.
5477db96d56Sopenharmony_ci
5487db96d56Sopenharmony_ci
5497db96d56Sopenharmony_ci   .. method:: release()
5507db96d56Sopenharmony_ci
5517db96d56Sopenharmony_ci      Release a lock.  This can be called from any thread, not only the thread
5527db96d56Sopenharmony_ci      which has acquired the lock.
5537db96d56Sopenharmony_ci
5547db96d56Sopenharmony_ci      When the lock is locked, reset it to unlocked, and return.  If any other threads
5557db96d56Sopenharmony_ci      are blocked waiting for the lock to become unlocked, allow exactly one of them
5567db96d56Sopenharmony_ci      to proceed.
5577db96d56Sopenharmony_ci
5587db96d56Sopenharmony_ci      When invoked on an unlocked lock, a :exc:`RuntimeError` is raised.
5597db96d56Sopenharmony_ci
5607db96d56Sopenharmony_ci      There is no return value.
5617db96d56Sopenharmony_ci
5627db96d56Sopenharmony_ci   .. method:: locked()
5637db96d56Sopenharmony_ci
5647db96d56Sopenharmony_ci      Return ``True`` if the lock is acquired.
5657db96d56Sopenharmony_ci
5667db96d56Sopenharmony_ci
5677db96d56Sopenharmony_ci
5687db96d56Sopenharmony_ci.. _rlock-objects:
5697db96d56Sopenharmony_ci
5707db96d56Sopenharmony_ciRLock Objects
5717db96d56Sopenharmony_ci-------------
5727db96d56Sopenharmony_ci
5737db96d56Sopenharmony_ciA reentrant lock is a synchronization primitive that may be acquired multiple
5747db96d56Sopenharmony_citimes by the same thread.  Internally, it uses the concepts of "owning thread"
5757db96d56Sopenharmony_ciand "recursion level" in addition to the locked/unlocked state used by primitive
5767db96d56Sopenharmony_cilocks.  In the locked state, some thread owns the lock; in the unlocked state,
5777db96d56Sopenharmony_cino thread owns it.
5787db96d56Sopenharmony_ci
5797db96d56Sopenharmony_ciTo lock the lock, a thread calls its :meth:`~RLock.acquire` method; this
5807db96d56Sopenharmony_cireturns once the thread owns the lock.  To unlock the lock, a thread calls
5817db96d56Sopenharmony_ciits :meth:`~Lock.release` method. :meth:`~Lock.acquire`/:meth:`~Lock.release`
5827db96d56Sopenharmony_cicall pairs may be nested; only the final :meth:`~Lock.release` (the
5837db96d56Sopenharmony_ci:meth:`~Lock.release` of the outermost pair) resets the lock to unlocked and
5847db96d56Sopenharmony_ciallows another thread blocked in :meth:`~Lock.acquire` to proceed.
5857db96d56Sopenharmony_ci
5867db96d56Sopenharmony_ciReentrant locks also support the :ref:`context management protocol <with-locks>`.
5877db96d56Sopenharmony_ci
5887db96d56Sopenharmony_ci
5897db96d56Sopenharmony_ci.. class:: RLock()
5907db96d56Sopenharmony_ci
5917db96d56Sopenharmony_ci   This class implements reentrant lock objects.  A reentrant lock must be
5927db96d56Sopenharmony_ci   released by the thread that acquired it.  Once a thread has acquired a
5937db96d56Sopenharmony_ci   reentrant lock, the same thread may acquire it again without blocking; the
5947db96d56Sopenharmony_ci   thread must release it once for each time it has acquired it.
5957db96d56Sopenharmony_ci
5967db96d56Sopenharmony_ci   Note that ``RLock`` is actually a factory function which returns an instance
5977db96d56Sopenharmony_ci   of the most efficient version of the concrete RLock class that is supported
5987db96d56Sopenharmony_ci   by the platform.
5997db96d56Sopenharmony_ci
6007db96d56Sopenharmony_ci
6017db96d56Sopenharmony_ci   .. method:: acquire(blocking=True, timeout=-1)
6027db96d56Sopenharmony_ci
6037db96d56Sopenharmony_ci      Acquire a lock, blocking or non-blocking.
6047db96d56Sopenharmony_ci
6057db96d56Sopenharmony_ci      When invoked without arguments: if this thread already owns the lock, increment
6067db96d56Sopenharmony_ci      the recursion level by one, and return immediately.  Otherwise, if another
6077db96d56Sopenharmony_ci      thread owns the lock, block until the lock is unlocked.  Once the lock is
6087db96d56Sopenharmony_ci      unlocked (not owned by any thread), then grab ownership, set the recursion level
6097db96d56Sopenharmony_ci      to one, and return.  If more than one thread is blocked waiting until the lock
6107db96d56Sopenharmony_ci      is unlocked, only one at a time will be able to grab ownership of the lock.
6117db96d56Sopenharmony_ci      There is no return value in this case.
6127db96d56Sopenharmony_ci
6137db96d56Sopenharmony_ci      When invoked with the *blocking* argument set to ``True``, do the same thing as when
6147db96d56Sopenharmony_ci      called without arguments, and return ``True``.
6157db96d56Sopenharmony_ci
6167db96d56Sopenharmony_ci      When invoked with the *blocking* argument set to ``False``, do not block.  If a call
6177db96d56Sopenharmony_ci      without an argument would block, return ``False`` immediately; otherwise, do the
6187db96d56Sopenharmony_ci      same thing as when called without arguments, and return ``True``.
6197db96d56Sopenharmony_ci
6207db96d56Sopenharmony_ci      When invoked with the floating-point *timeout* argument set to a positive
6217db96d56Sopenharmony_ci      value, block for at most the number of seconds specified by *timeout*
6227db96d56Sopenharmony_ci      and as long as the lock cannot be acquired.  Return ``True`` if the lock has
6237db96d56Sopenharmony_ci      been acquired, ``False`` if the timeout has elapsed.
6247db96d56Sopenharmony_ci
6257db96d56Sopenharmony_ci      .. versionchanged:: 3.2
6267db96d56Sopenharmony_ci         The *timeout* parameter is new.
6277db96d56Sopenharmony_ci
6287db96d56Sopenharmony_ci
6297db96d56Sopenharmony_ci   .. method:: release()
6307db96d56Sopenharmony_ci
6317db96d56Sopenharmony_ci      Release a lock, decrementing the recursion level.  If after the decrement it is
6327db96d56Sopenharmony_ci      zero, reset the lock to unlocked (not owned by any thread), and if any other
6337db96d56Sopenharmony_ci      threads are blocked waiting for the lock to become unlocked, allow exactly one
6347db96d56Sopenharmony_ci      of them to proceed.  If after the decrement the recursion level is still
6357db96d56Sopenharmony_ci      nonzero, the lock remains locked and owned by the calling thread.
6367db96d56Sopenharmony_ci
6377db96d56Sopenharmony_ci      Only call this method when the calling thread owns the lock. A
6387db96d56Sopenharmony_ci      :exc:`RuntimeError` is raised if this method is called when the lock is
6397db96d56Sopenharmony_ci      unlocked.
6407db96d56Sopenharmony_ci
6417db96d56Sopenharmony_ci      There is no return value.
6427db96d56Sopenharmony_ci
6437db96d56Sopenharmony_ci
6447db96d56Sopenharmony_ci.. _condition-objects:
6457db96d56Sopenharmony_ci
6467db96d56Sopenharmony_ciCondition Objects
6477db96d56Sopenharmony_ci-----------------
6487db96d56Sopenharmony_ci
6497db96d56Sopenharmony_ciA condition variable is always associated with some kind of lock; this can be
6507db96d56Sopenharmony_cipassed in or one will be created by default.  Passing one in is useful when
6517db96d56Sopenharmony_ciseveral condition variables must share the same lock.  The lock is part of
6527db96d56Sopenharmony_cithe condition object: you don't have to track it separately.
6537db96d56Sopenharmony_ci
6547db96d56Sopenharmony_ciA condition variable obeys the :ref:`context management protocol <with-locks>`:
6557db96d56Sopenharmony_ciusing the ``with`` statement acquires the associated lock for the duration of
6567db96d56Sopenharmony_cithe enclosed block.  The :meth:`~Condition.acquire` and
6577db96d56Sopenharmony_ci:meth:`~Condition.release` methods also call the corresponding methods of
6587db96d56Sopenharmony_cithe associated lock.
6597db96d56Sopenharmony_ci
6607db96d56Sopenharmony_ciOther methods must be called with the associated lock held.  The
6617db96d56Sopenharmony_ci:meth:`~Condition.wait` method releases the lock, and then blocks until
6627db96d56Sopenharmony_cianother thread awakens it by calling :meth:`~Condition.notify` or
6637db96d56Sopenharmony_ci:meth:`~Condition.notify_all`.  Once awakened, :meth:`~Condition.wait`
6647db96d56Sopenharmony_cire-acquires the lock and returns.  It is also possible to specify a timeout.
6657db96d56Sopenharmony_ci
6667db96d56Sopenharmony_ciThe :meth:`~Condition.notify` method wakes up one of the threads waiting for
6677db96d56Sopenharmony_cithe condition variable, if any are waiting.  The :meth:`~Condition.notify_all`
6687db96d56Sopenharmony_cimethod wakes up all threads waiting for the condition variable.
6697db96d56Sopenharmony_ci
6707db96d56Sopenharmony_ciNote: the :meth:`~Condition.notify` and :meth:`~Condition.notify_all` methods
6717db96d56Sopenharmony_cidon't release the lock; this means that the thread or threads awakened will
6727db96d56Sopenharmony_cinot return from their :meth:`~Condition.wait` call immediately, but only when
6737db96d56Sopenharmony_cithe thread that called :meth:`~Condition.notify` or :meth:`~Condition.notify_all`
6747db96d56Sopenharmony_cifinally relinquishes ownership of the lock.
6757db96d56Sopenharmony_ci
6767db96d56Sopenharmony_ciThe typical programming style using condition variables uses the lock to
6777db96d56Sopenharmony_cisynchronize access to some shared state; threads that are interested in a
6787db96d56Sopenharmony_ciparticular change of state call :meth:`~Condition.wait` repeatedly until they
6797db96d56Sopenharmony_cisee the desired state, while threads that modify the state call
6807db96d56Sopenharmony_ci:meth:`~Condition.notify` or :meth:`~Condition.notify_all` when they change
6817db96d56Sopenharmony_cithe state in such a way that it could possibly be a desired state for one
6827db96d56Sopenharmony_ciof the waiters.  For example, the following code is a generic
6837db96d56Sopenharmony_ciproducer-consumer situation with unlimited buffer capacity::
6847db96d56Sopenharmony_ci
6857db96d56Sopenharmony_ci   # Consume one item
6867db96d56Sopenharmony_ci   with cv:
6877db96d56Sopenharmony_ci       while not an_item_is_available():
6887db96d56Sopenharmony_ci           cv.wait()
6897db96d56Sopenharmony_ci       get_an_available_item()
6907db96d56Sopenharmony_ci
6917db96d56Sopenharmony_ci   # Produce one item
6927db96d56Sopenharmony_ci   with cv:
6937db96d56Sopenharmony_ci       make_an_item_available()
6947db96d56Sopenharmony_ci       cv.notify()
6957db96d56Sopenharmony_ci
6967db96d56Sopenharmony_ciThe ``while`` loop checking for the application's condition is necessary
6977db96d56Sopenharmony_cibecause :meth:`~Condition.wait` can return after an arbitrary long time,
6987db96d56Sopenharmony_ciand the condition which prompted the :meth:`~Condition.notify` call may
6997db96d56Sopenharmony_cino longer hold true.  This is inherent to multi-threaded programming.  The
7007db96d56Sopenharmony_ci:meth:`~Condition.wait_for` method can be used to automate the condition
7017db96d56Sopenharmony_cichecking, and eases the computation of timeouts::
7027db96d56Sopenharmony_ci
7037db96d56Sopenharmony_ci   # Consume an item
7047db96d56Sopenharmony_ci   with cv:
7057db96d56Sopenharmony_ci       cv.wait_for(an_item_is_available)
7067db96d56Sopenharmony_ci       get_an_available_item()
7077db96d56Sopenharmony_ci
7087db96d56Sopenharmony_ciTo choose between :meth:`~Condition.notify` and :meth:`~Condition.notify_all`,
7097db96d56Sopenharmony_ciconsider whether one state change can be interesting for only one or several
7107db96d56Sopenharmony_ciwaiting threads.  E.g. in a typical producer-consumer situation, adding one
7117db96d56Sopenharmony_ciitem to the buffer only needs to wake up one consumer thread.
7127db96d56Sopenharmony_ci
7137db96d56Sopenharmony_ci
7147db96d56Sopenharmony_ci.. class:: Condition(lock=None)
7157db96d56Sopenharmony_ci
7167db96d56Sopenharmony_ci   This class implements condition variable objects.  A condition variable
7177db96d56Sopenharmony_ci   allows one or more threads to wait until they are notified by another thread.
7187db96d56Sopenharmony_ci
7197db96d56Sopenharmony_ci   If the *lock* argument is given and not ``None``, it must be a :class:`Lock`
7207db96d56Sopenharmony_ci   or :class:`RLock` object, and it is used as the underlying lock.  Otherwise,
7217db96d56Sopenharmony_ci   a new :class:`RLock` object is created and used as the underlying lock.
7227db96d56Sopenharmony_ci
7237db96d56Sopenharmony_ci   .. versionchanged:: 3.3
7247db96d56Sopenharmony_ci      changed from a factory function to a class.
7257db96d56Sopenharmony_ci
7267db96d56Sopenharmony_ci   .. method:: acquire(*args)
7277db96d56Sopenharmony_ci
7287db96d56Sopenharmony_ci      Acquire the underlying lock. This method calls the corresponding method on
7297db96d56Sopenharmony_ci      the underlying lock; the return value is whatever that method returns.
7307db96d56Sopenharmony_ci
7317db96d56Sopenharmony_ci   .. method:: release()
7327db96d56Sopenharmony_ci
7337db96d56Sopenharmony_ci      Release the underlying lock. This method calls the corresponding method on
7347db96d56Sopenharmony_ci      the underlying lock; there is no return value.
7357db96d56Sopenharmony_ci
7367db96d56Sopenharmony_ci   .. method:: wait(timeout=None)
7377db96d56Sopenharmony_ci
7387db96d56Sopenharmony_ci      Wait until notified or until a timeout occurs. If the calling thread has
7397db96d56Sopenharmony_ci      not acquired the lock when this method is called, a :exc:`RuntimeError` is
7407db96d56Sopenharmony_ci      raised.
7417db96d56Sopenharmony_ci
7427db96d56Sopenharmony_ci      This method releases the underlying lock, and then blocks until it is
7437db96d56Sopenharmony_ci      awakened by a :meth:`notify` or :meth:`notify_all` call for the same
7447db96d56Sopenharmony_ci      condition variable in another thread, or until the optional timeout
7457db96d56Sopenharmony_ci      occurs.  Once awakened or timed out, it re-acquires the lock and returns.
7467db96d56Sopenharmony_ci
7477db96d56Sopenharmony_ci      When the *timeout* argument is present and not ``None``, it should be a
7487db96d56Sopenharmony_ci      floating point number specifying a timeout for the operation in seconds
7497db96d56Sopenharmony_ci      (or fractions thereof).
7507db96d56Sopenharmony_ci
7517db96d56Sopenharmony_ci      When the underlying lock is an :class:`RLock`, it is not released using
7527db96d56Sopenharmony_ci      its :meth:`release` method, since this may not actually unlock the lock
7537db96d56Sopenharmony_ci      when it was acquired multiple times recursively.  Instead, an internal
7547db96d56Sopenharmony_ci      interface of the :class:`RLock` class is used, which really unlocks it
7557db96d56Sopenharmony_ci      even when it has been recursively acquired several times. Another internal
7567db96d56Sopenharmony_ci      interface is then used to restore the recursion level when the lock is
7577db96d56Sopenharmony_ci      reacquired.
7587db96d56Sopenharmony_ci
7597db96d56Sopenharmony_ci      The return value is ``True`` unless a given *timeout* expired, in which
7607db96d56Sopenharmony_ci      case it is ``False``.
7617db96d56Sopenharmony_ci
7627db96d56Sopenharmony_ci      .. versionchanged:: 3.2
7637db96d56Sopenharmony_ci         Previously, the method always returned ``None``.
7647db96d56Sopenharmony_ci
7657db96d56Sopenharmony_ci   .. method:: wait_for(predicate, timeout=None)
7667db96d56Sopenharmony_ci
7677db96d56Sopenharmony_ci      Wait until a condition evaluates to true.  *predicate* should be a
7687db96d56Sopenharmony_ci      callable which result will be interpreted as a boolean value.
7697db96d56Sopenharmony_ci      A *timeout* may be provided giving the maximum time to wait.
7707db96d56Sopenharmony_ci
7717db96d56Sopenharmony_ci      This utility method may call :meth:`wait` repeatedly until the predicate
7727db96d56Sopenharmony_ci      is satisfied, or until a timeout occurs. The return value is
7737db96d56Sopenharmony_ci      the last return value of the predicate and will evaluate to
7747db96d56Sopenharmony_ci      ``False`` if the method timed out.
7757db96d56Sopenharmony_ci
7767db96d56Sopenharmony_ci      Ignoring the timeout feature, calling this method is roughly equivalent to
7777db96d56Sopenharmony_ci      writing::
7787db96d56Sopenharmony_ci
7797db96d56Sopenharmony_ci        while not predicate():
7807db96d56Sopenharmony_ci            cv.wait()
7817db96d56Sopenharmony_ci
7827db96d56Sopenharmony_ci      Therefore, the same rules apply as with :meth:`wait`: The lock must be
7837db96d56Sopenharmony_ci      held when called and is re-acquired on return.  The predicate is evaluated
7847db96d56Sopenharmony_ci      with the lock held.
7857db96d56Sopenharmony_ci
7867db96d56Sopenharmony_ci      .. versionadded:: 3.2
7877db96d56Sopenharmony_ci
7887db96d56Sopenharmony_ci   .. method:: notify(n=1)
7897db96d56Sopenharmony_ci
7907db96d56Sopenharmony_ci      By default, wake up one thread waiting on this condition, if any.  If the
7917db96d56Sopenharmony_ci      calling thread has not acquired the lock when this method is called, a
7927db96d56Sopenharmony_ci      :exc:`RuntimeError` is raised.
7937db96d56Sopenharmony_ci
7947db96d56Sopenharmony_ci      This method wakes up at most *n* of the threads waiting for the condition
7957db96d56Sopenharmony_ci      variable; it is a no-op if no threads are waiting.
7967db96d56Sopenharmony_ci
7977db96d56Sopenharmony_ci      The current implementation wakes up exactly *n* threads, if at least *n*
7987db96d56Sopenharmony_ci      threads are waiting.  However, it's not safe to rely on this behavior.
7997db96d56Sopenharmony_ci      A future, optimized implementation may occasionally wake up more than
8007db96d56Sopenharmony_ci      *n* threads.
8017db96d56Sopenharmony_ci
8027db96d56Sopenharmony_ci      Note: an awakened thread does not actually return from its :meth:`wait`
8037db96d56Sopenharmony_ci      call until it can reacquire the lock.  Since :meth:`notify` does not
8047db96d56Sopenharmony_ci      release the lock, its caller should.
8057db96d56Sopenharmony_ci
8067db96d56Sopenharmony_ci   .. method:: notify_all()
8077db96d56Sopenharmony_ci
8087db96d56Sopenharmony_ci      Wake up all threads waiting on this condition.  This method acts like
8097db96d56Sopenharmony_ci      :meth:`notify`, but wakes up all waiting threads instead of one. If the
8107db96d56Sopenharmony_ci      calling thread has not acquired the lock when this method is called, a
8117db96d56Sopenharmony_ci      :exc:`RuntimeError` is raised.
8127db96d56Sopenharmony_ci
8137db96d56Sopenharmony_ci      The method ``notifyAll`` is a deprecated alias for this method.
8147db96d56Sopenharmony_ci
8157db96d56Sopenharmony_ci
8167db96d56Sopenharmony_ci.. _semaphore-objects:
8177db96d56Sopenharmony_ci
8187db96d56Sopenharmony_ciSemaphore Objects
8197db96d56Sopenharmony_ci-----------------
8207db96d56Sopenharmony_ci
8217db96d56Sopenharmony_ciThis is one of the oldest synchronization primitives in the history of computer
8227db96d56Sopenharmony_ciscience, invented by the early Dutch computer scientist Edsger W. Dijkstra (he
8237db96d56Sopenharmony_ciused the names ``P()`` and ``V()`` instead of :meth:`~Semaphore.acquire` and
8247db96d56Sopenharmony_ci:meth:`~Semaphore.release`).
8257db96d56Sopenharmony_ci
8267db96d56Sopenharmony_ciA semaphore manages an internal counter which is decremented by each
8277db96d56Sopenharmony_ci:meth:`~Semaphore.acquire` call and incremented by each :meth:`~Semaphore.release`
8287db96d56Sopenharmony_cicall.  The counter can never go below zero; when :meth:`~Semaphore.acquire`
8297db96d56Sopenharmony_cifinds that it is zero, it blocks, waiting until some other thread calls
8307db96d56Sopenharmony_ci:meth:`~Semaphore.release`.
8317db96d56Sopenharmony_ci
8327db96d56Sopenharmony_ciSemaphores also support the :ref:`context management protocol <with-locks>`.
8337db96d56Sopenharmony_ci
8347db96d56Sopenharmony_ci
8357db96d56Sopenharmony_ci.. class:: Semaphore(value=1)
8367db96d56Sopenharmony_ci
8377db96d56Sopenharmony_ci   This class implements semaphore objects.  A semaphore manages an atomic
8387db96d56Sopenharmony_ci   counter representing the number of :meth:`release` calls minus the number of
8397db96d56Sopenharmony_ci   :meth:`acquire` calls, plus an initial value.  The :meth:`acquire` method
8407db96d56Sopenharmony_ci   blocks if necessary until it can return without making the counter negative.
8417db96d56Sopenharmony_ci   If not given, *value* defaults to 1.
8427db96d56Sopenharmony_ci
8437db96d56Sopenharmony_ci   The optional argument gives the initial *value* for the internal counter; it
8447db96d56Sopenharmony_ci   defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is
8457db96d56Sopenharmony_ci   raised.
8467db96d56Sopenharmony_ci
8477db96d56Sopenharmony_ci   .. versionchanged:: 3.3
8487db96d56Sopenharmony_ci      changed from a factory function to a class.
8497db96d56Sopenharmony_ci
8507db96d56Sopenharmony_ci   .. method:: acquire(blocking=True, timeout=None)
8517db96d56Sopenharmony_ci
8527db96d56Sopenharmony_ci      Acquire a semaphore.
8537db96d56Sopenharmony_ci
8547db96d56Sopenharmony_ci      When invoked without arguments:
8557db96d56Sopenharmony_ci
8567db96d56Sopenharmony_ci      * If the internal counter is larger than zero on entry, decrement it by
8577db96d56Sopenharmony_ci        one and return ``True`` immediately.
8587db96d56Sopenharmony_ci      * If the internal counter is zero on entry, block until awoken by a call to
8597db96d56Sopenharmony_ci        :meth:`~Semaphore.release`.  Once awoken (and the counter is greater
8607db96d56Sopenharmony_ci        than 0), decrement the counter by 1 and return ``True``.  Exactly one
8617db96d56Sopenharmony_ci        thread will be awoken by each call to :meth:`~Semaphore.release`.  The
8627db96d56Sopenharmony_ci        order in which threads are awoken should not be relied on.
8637db96d56Sopenharmony_ci
8647db96d56Sopenharmony_ci      When invoked with *blocking* set to ``False``, do not block.  If a call
8657db96d56Sopenharmony_ci      without an argument would block, return ``False`` immediately; otherwise, do
8667db96d56Sopenharmony_ci      the same thing as when called without arguments, and return ``True``.
8677db96d56Sopenharmony_ci
8687db96d56Sopenharmony_ci      When invoked with a *timeout* other than ``None``, it will block for at
8697db96d56Sopenharmony_ci      most *timeout* seconds.  If acquire does not complete successfully in
8707db96d56Sopenharmony_ci      that interval, return ``False``.  Return ``True`` otherwise.
8717db96d56Sopenharmony_ci
8727db96d56Sopenharmony_ci      .. versionchanged:: 3.2
8737db96d56Sopenharmony_ci         The *timeout* parameter is new.
8747db96d56Sopenharmony_ci
8757db96d56Sopenharmony_ci   .. method:: release(n=1)
8767db96d56Sopenharmony_ci
8777db96d56Sopenharmony_ci      Release a semaphore, incrementing the internal counter by *n*.  When it
8787db96d56Sopenharmony_ci      was zero on entry and other threads are waiting for it to become larger
8797db96d56Sopenharmony_ci      than zero again, wake up *n* of those threads.
8807db96d56Sopenharmony_ci
8817db96d56Sopenharmony_ci      .. versionchanged:: 3.9
8827db96d56Sopenharmony_ci         Added the *n* parameter to release multiple waiting threads at once.
8837db96d56Sopenharmony_ci
8847db96d56Sopenharmony_ci
8857db96d56Sopenharmony_ci.. class:: BoundedSemaphore(value=1)
8867db96d56Sopenharmony_ci
8877db96d56Sopenharmony_ci   Class implementing bounded semaphore objects.  A bounded semaphore checks to
8887db96d56Sopenharmony_ci   make sure its current value doesn't exceed its initial value.  If it does,
8897db96d56Sopenharmony_ci   :exc:`ValueError` is raised. In most situations semaphores are used to guard
8907db96d56Sopenharmony_ci   resources with limited capacity.  If the semaphore is released too many times
8917db96d56Sopenharmony_ci   it's a sign of a bug.  If not given, *value* defaults to 1.
8927db96d56Sopenharmony_ci
8937db96d56Sopenharmony_ci   .. versionchanged:: 3.3
8947db96d56Sopenharmony_ci      changed from a factory function to a class.
8957db96d56Sopenharmony_ci
8967db96d56Sopenharmony_ci
8977db96d56Sopenharmony_ci.. _semaphore-examples:
8987db96d56Sopenharmony_ci
8997db96d56Sopenharmony_ci:class:`Semaphore` Example
9007db96d56Sopenharmony_ci^^^^^^^^^^^^^^^^^^^^^^^^^^
9017db96d56Sopenharmony_ci
9027db96d56Sopenharmony_ciSemaphores are often used to guard resources with limited capacity, for example,
9037db96d56Sopenharmony_cia database server.  In any situation where the size of the resource is fixed,
9047db96d56Sopenharmony_ciyou should use a bounded semaphore.  Before spawning any worker threads, your
9057db96d56Sopenharmony_cimain thread would initialize the semaphore::
9067db96d56Sopenharmony_ci
9077db96d56Sopenharmony_ci   maxconnections = 5
9087db96d56Sopenharmony_ci   # ...
9097db96d56Sopenharmony_ci   pool_sema = BoundedSemaphore(value=maxconnections)
9107db96d56Sopenharmony_ci
9117db96d56Sopenharmony_ciOnce spawned, worker threads call the semaphore's acquire and release methods
9127db96d56Sopenharmony_ciwhen they need to connect to the server::
9137db96d56Sopenharmony_ci
9147db96d56Sopenharmony_ci   with pool_sema:
9157db96d56Sopenharmony_ci       conn = connectdb()
9167db96d56Sopenharmony_ci       try:
9177db96d56Sopenharmony_ci           # ... use connection ...
9187db96d56Sopenharmony_ci       finally:
9197db96d56Sopenharmony_ci           conn.close()
9207db96d56Sopenharmony_ci
9217db96d56Sopenharmony_ciThe use of a bounded semaphore reduces the chance that a programming error which
9227db96d56Sopenharmony_cicauses the semaphore to be released more than it's acquired will go undetected.
9237db96d56Sopenharmony_ci
9247db96d56Sopenharmony_ci
9257db96d56Sopenharmony_ci.. _event-objects:
9267db96d56Sopenharmony_ci
9277db96d56Sopenharmony_ciEvent Objects
9287db96d56Sopenharmony_ci-------------
9297db96d56Sopenharmony_ci
9307db96d56Sopenharmony_ciThis is one of the simplest mechanisms for communication between threads: one
9317db96d56Sopenharmony_cithread signals an event and other threads wait for it.
9327db96d56Sopenharmony_ci
9337db96d56Sopenharmony_ciAn event object manages an internal flag that can be set to true with the
9347db96d56Sopenharmony_ci:meth:`~Event.set` method and reset to false with the :meth:`~Event.clear`
9357db96d56Sopenharmony_cimethod.  The :meth:`~Event.wait` method blocks until the flag is true.
9367db96d56Sopenharmony_ci
9377db96d56Sopenharmony_ci
9387db96d56Sopenharmony_ci.. class:: Event()
9397db96d56Sopenharmony_ci
9407db96d56Sopenharmony_ci   Class implementing event objects.  An event manages a flag that can be set to
9417db96d56Sopenharmony_ci   true with the :meth:`~Event.set` method and reset to false with the
9427db96d56Sopenharmony_ci   :meth:`clear` method.  The :meth:`wait` method blocks until the flag is true.
9437db96d56Sopenharmony_ci   The flag is initially false.
9447db96d56Sopenharmony_ci
9457db96d56Sopenharmony_ci   .. versionchanged:: 3.3
9467db96d56Sopenharmony_ci      changed from a factory function to a class.
9477db96d56Sopenharmony_ci
9487db96d56Sopenharmony_ci   .. method:: is_set()
9497db96d56Sopenharmony_ci
9507db96d56Sopenharmony_ci      Return ``True`` if and only if the internal flag is true.
9517db96d56Sopenharmony_ci
9527db96d56Sopenharmony_ci      The method ``isSet`` is a deprecated alias for this method.
9537db96d56Sopenharmony_ci
9547db96d56Sopenharmony_ci   .. method:: set()
9557db96d56Sopenharmony_ci
9567db96d56Sopenharmony_ci      Set the internal flag to true. All threads waiting for it to become true
9577db96d56Sopenharmony_ci      are awakened. Threads that call :meth:`wait` once the flag is true will
9587db96d56Sopenharmony_ci      not block at all.
9597db96d56Sopenharmony_ci
9607db96d56Sopenharmony_ci   .. method:: clear()
9617db96d56Sopenharmony_ci
9627db96d56Sopenharmony_ci      Reset the internal flag to false. Subsequently, threads calling
9637db96d56Sopenharmony_ci      :meth:`wait` will block until :meth:`.set` is called to set the internal
9647db96d56Sopenharmony_ci      flag to true again.
9657db96d56Sopenharmony_ci
9667db96d56Sopenharmony_ci   .. method:: wait(timeout=None)
9677db96d56Sopenharmony_ci
9687db96d56Sopenharmony_ci      Block until the internal flag is true.  If the internal flag is true on
9697db96d56Sopenharmony_ci      entry, return immediately.  Otherwise, block until another thread calls
9707db96d56Sopenharmony_ci      :meth:`.set` to set the flag to true, or until the optional timeout occurs.
9717db96d56Sopenharmony_ci
9727db96d56Sopenharmony_ci      When the timeout argument is present and not ``None``, it should be a
9737db96d56Sopenharmony_ci      floating point number specifying a timeout for the operation in seconds
9747db96d56Sopenharmony_ci      (or fractions thereof).
9757db96d56Sopenharmony_ci
9767db96d56Sopenharmony_ci      This method returns ``True`` if and only if the internal flag has been set to
9777db96d56Sopenharmony_ci      true, either before the wait call or after the wait starts, so it will
9787db96d56Sopenharmony_ci      always return ``True`` except if a timeout is given and the operation
9797db96d56Sopenharmony_ci      times out.
9807db96d56Sopenharmony_ci
9817db96d56Sopenharmony_ci      .. versionchanged:: 3.1
9827db96d56Sopenharmony_ci         Previously, the method always returned ``None``.
9837db96d56Sopenharmony_ci
9847db96d56Sopenharmony_ci
9857db96d56Sopenharmony_ci.. _timer-objects:
9867db96d56Sopenharmony_ci
9877db96d56Sopenharmony_ciTimer Objects
9887db96d56Sopenharmony_ci-------------
9897db96d56Sopenharmony_ci
9907db96d56Sopenharmony_ciThis class represents an action that should be run only after a certain amount
9917db96d56Sopenharmony_ciof time has passed --- a timer.  :class:`Timer` is a subclass of :class:`Thread`
9927db96d56Sopenharmony_ciand as such also functions as an example of creating custom threads.
9937db96d56Sopenharmony_ci
9947db96d56Sopenharmony_ciTimers are started, as with threads, by calling their :meth:`~Timer.start`
9957db96d56Sopenharmony_cimethod.  The timer can be stopped (before its action has begun) by calling the
9967db96d56Sopenharmony_ci:meth:`~Timer.cancel` method.  The interval the timer will wait before
9977db96d56Sopenharmony_ciexecuting its action may not be exactly the same as the interval specified by
9987db96d56Sopenharmony_cithe user.
9997db96d56Sopenharmony_ci
10007db96d56Sopenharmony_ciFor example::
10017db96d56Sopenharmony_ci
10027db96d56Sopenharmony_ci   def hello():
10037db96d56Sopenharmony_ci       print("hello, world")
10047db96d56Sopenharmony_ci
10057db96d56Sopenharmony_ci   t = Timer(30.0, hello)
10067db96d56Sopenharmony_ci   t.start()  # after 30 seconds, "hello, world" will be printed
10077db96d56Sopenharmony_ci
10087db96d56Sopenharmony_ci
10097db96d56Sopenharmony_ci.. class:: Timer(interval, function, args=None, kwargs=None)
10107db96d56Sopenharmony_ci
10117db96d56Sopenharmony_ci   Create a timer that will run *function* with arguments *args* and  keyword
10127db96d56Sopenharmony_ci   arguments *kwargs*, after *interval* seconds have passed.
10137db96d56Sopenharmony_ci   If *args* is ``None`` (the default) then an empty list will be used.
10147db96d56Sopenharmony_ci   If *kwargs* is ``None`` (the default) then an empty dict will be used.
10157db96d56Sopenharmony_ci
10167db96d56Sopenharmony_ci   .. versionchanged:: 3.3
10177db96d56Sopenharmony_ci      changed from a factory function to a class.
10187db96d56Sopenharmony_ci
10197db96d56Sopenharmony_ci   .. method:: cancel()
10207db96d56Sopenharmony_ci
10217db96d56Sopenharmony_ci      Stop the timer, and cancel the execution of the timer's action.  This will
10227db96d56Sopenharmony_ci      only work if the timer is still in its waiting stage.
10237db96d56Sopenharmony_ci
10247db96d56Sopenharmony_ci
10257db96d56Sopenharmony_ciBarrier Objects
10267db96d56Sopenharmony_ci---------------
10277db96d56Sopenharmony_ci
10287db96d56Sopenharmony_ci.. versionadded:: 3.2
10297db96d56Sopenharmony_ci
10307db96d56Sopenharmony_ciThis class provides a simple synchronization primitive for use by a fixed number
10317db96d56Sopenharmony_ciof threads that need to wait for each other.  Each of the threads tries to pass
10327db96d56Sopenharmony_cithe barrier by calling the :meth:`~Barrier.wait` method and will block until
10337db96d56Sopenharmony_ciall of the threads have made their :meth:`~Barrier.wait` calls. At this point,
10347db96d56Sopenharmony_cithe threads are released simultaneously.
10357db96d56Sopenharmony_ci
10367db96d56Sopenharmony_ciThe barrier can be reused any number of times for the same number of threads.
10377db96d56Sopenharmony_ci
10387db96d56Sopenharmony_ciAs an example, here is a simple way to synchronize a client and server thread::
10397db96d56Sopenharmony_ci
10407db96d56Sopenharmony_ci   b = Barrier(2, timeout=5)
10417db96d56Sopenharmony_ci
10427db96d56Sopenharmony_ci   def server():
10437db96d56Sopenharmony_ci       start_server()
10447db96d56Sopenharmony_ci       b.wait()
10457db96d56Sopenharmony_ci       while True:
10467db96d56Sopenharmony_ci           connection = accept_connection()
10477db96d56Sopenharmony_ci           process_server_connection(connection)
10487db96d56Sopenharmony_ci
10497db96d56Sopenharmony_ci   def client():
10507db96d56Sopenharmony_ci       b.wait()
10517db96d56Sopenharmony_ci       while True:
10527db96d56Sopenharmony_ci           connection = make_connection()
10537db96d56Sopenharmony_ci           process_client_connection(connection)
10547db96d56Sopenharmony_ci
10557db96d56Sopenharmony_ci
10567db96d56Sopenharmony_ci.. class:: Barrier(parties, action=None, timeout=None)
10577db96d56Sopenharmony_ci
10587db96d56Sopenharmony_ci   Create a barrier object for *parties* number of threads.  An *action*, when
10597db96d56Sopenharmony_ci   provided, is a callable to be called by one of the threads when they are
10607db96d56Sopenharmony_ci   released.  *timeout* is the default timeout value if none is specified for
10617db96d56Sopenharmony_ci   the :meth:`wait` method.
10627db96d56Sopenharmony_ci
10637db96d56Sopenharmony_ci   .. method:: wait(timeout=None)
10647db96d56Sopenharmony_ci
10657db96d56Sopenharmony_ci      Pass the barrier.  When all the threads party to the barrier have called
10667db96d56Sopenharmony_ci      this function, they are all released simultaneously.  If a *timeout* is
10677db96d56Sopenharmony_ci      provided, it is used in preference to any that was supplied to the class
10687db96d56Sopenharmony_ci      constructor.
10697db96d56Sopenharmony_ci
10707db96d56Sopenharmony_ci      The return value is an integer in the range 0 to *parties* -- 1, different
10717db96d56Sopenharmony_ci      for each thread.  This can be used to select a thread to do some special
10727db96d56Sopenharmony_ci      housekeeping, e.g.::
10737db96d56Sopenharmony_ci
10747db96d56Sopenharmony_ci         i = barrier.wait()
10757db96d56Sopenharmony_ci         if i == 0:
10767db96d56Sopenharmony_ci             # Only one thread needs to print this
10777db96d56Sopenharmony_ci             print("passed the barrier")
10787db96d56Sopenharmony_ci
10797db96d56Sopenharmony_ci      If an *action* was provided to the constructor, one of the threads will
10807db96d56Sopenharmony_ci      have called it prior to being released.  Should this call raise an error,
10817db96d56Sopenharmony_ci      the barrier is put into the broken state.
10827db96d56Sopenharmony_ci
10837db96d56Sopenharmony_ci      If the call times out, the barrier is put into the broken state.
10847db96d56Sopenharmony_ci
10857db96d56Sopenharmony_ci      This method may raise a :class:`BrokenBarrierError` exception if the
10867db96d56Sopenharmony_ci      barrier is broken or reset while a thread is waiting.
10877db96d56Sopenharmony_ci
10887db96d56Sopenharmony_ci   .. method:: reset()
10897db96d56Sopenharmony_ci
10907db96d56Sopenharmony_ci      Return the barrier to the default, empty state.  Any threads waiting on it
10917db96d56Sopenharmony_ci      will receive the :class:`BrokenBarrierError` exception.
10927db96d56Sopenharmony_ci
10937db96d56Sopenharmony_ci      Note that using this function may require some external
10947db96d56Sopenharmony_ci      synchronization if there are other threads whose state is unknown.  If a
10957db96d56Sopenharmony_ci      barrier is broken it may be better to just leave it and create a new one.
10967db96d56Sopenharmony_ci
10977db96d56Sopenharmony_ci   .. method:: abort()
10987db96d56Sopenharmony_ci
10997db96d56Sopenharmony_ci      Put the barrier into a broken state.  This causes any active or future
11007db96d56Sopenharmony_ci      calls to :meth:`wait` to fail with the :class:`BrokenBarrierError`.  Use
11017db96d56Sopenharmony_ci      this for example if one of the threads needs to abort, to avoid deadlocking the
11027db96d56Sopenharmony_ci      application.
11037db96d56Sopenharmony_ci
11047db96d56Sopenharmony_ci      It may be preferable to simply create the barrier with a sensible
11057db96d56Sopenharmony_ci      *timeout* value to automatically guard against one of the threads going
11067db96d56Sopenharmony_ci      awry.
11077db96d56Sopenharmony_ci
11087db96d56Sopenharmony_ci   .. attribute:: parties
11097db96d56Sopenharmony_ci
11107db96d56Sopenharmony_ci      The number of threads required to pass the barrier.
11117db96d56Sopenharmony_ci
11127db96d56Sopenharmony_ci   .. attribute:: n_waiting
11137db96d56Sopenharmony_ci
11147db96d56Sopenharmony_ci      The number of threads currently waiting in the barrier.
11157db96d56Sopenharmony_ci
11167db96d56Sopenharmony_ci   .. attribute:: broken
11177db96d56Sopenharmony_ci
11187db96d56Sopenharmony_ci      A boolean that is ``True`` if the barrier is in the broken state.
11197db96d56Sopenharmony_ci
11207db96d56Sopenharmony_ci
11217db96d56Sopenharmony_ci.. exception:: BrokenBarrierError
11227db96d56Sopenharmony_ci
11237db96d56Sopenharmony_ci   This exception, a subclass of :exc:`RuntimeError`, is raised when the
11247db96d56Sopenharmony_ci   :class:`Barrier` object is reset or broken.
11257db96d56Sopenharmony_ci
11267db96d56Sopenharmony_ci
11277db96d56Sopenharmony_ci.. _with-locks:
11287db96d56Sopenharmony_ci
11297db96d56Sopenharmony_ciUsing locks, conditions, and semaphores in the :keyword:`!with` statement
11307db96d56Sopenharmony_ci-------------------------------------------------------------------------
11317db96d56Sopenharmony_ci
11327db96d56Sopenharmony_ciAll of the objects provided by this module that have :meth:`acquire` and
11337db96d56Sopenharmony_ci:meth:`release` methods can be used as context managers for a :keyword:`with`
11347db96d56Sopenharmony_cistatement.  The :meth:`acquire` method will be called when the block is
11357db96d56Sopenharmony_cientered, and :meth:`release` will be called when the block is exited.  Hence,
11367db96d56Sopenharmony_cithe following snippet::
11377db96d56Sopenharmony_ci
11387db96d56Sopenharmony_ci   with some_lock:
11397db96d56Sopenharmony_ci       # do something...
11407db96d56Sopenharmony_ci
11417db96d56Sopenharmony_ciis equivalent to::
11427db96d56Sopenharmony_ci
11437db96d56Sopenharmony_ci   some_lock.acquire()
11447db96d56Sopenharmony_ci   try:
11457db96d56Sopenharmony_ci       # do something...
11467db96d56Sopenharmony_ci   finally:
11477db96d56Sopenharmony_ci       some_lock.release()
11487db96d56Sopenharmony_ci
11497db96d56Sopenharmony_ciCurrently, :class:`Lock`, :class:`RLock`, :class:`Condition`,
11507db96d56Sopenharmony_ci:class:`Semaphore`, and :class:`BoundedSemaphore` objects may be used as
11517db96d56Sopenharmony_ci:keyword:`with` statement context managers.
1152