Thread module in python example
Source code: Lib/threading.py Show
This module constructs higher-level threading interfaces on top of the lower level Changed in version 3.7: This module used to be optional, it is now always available. See also
Note In the Python 2.x series, this module contained CPython implementation detail: In CPython, due to the Global Interpreter Lock, only one thread can execute Python code at once
(even though certain performance-oriented libraries might overcome this limitation). If you want your application to make better use of the computational resources of multi-core machines, you are advised to use This module defines the following functions: threading. active_count ()¶Return the number of The function threading. current_thread ()¶Return the current
The function threading. excepthook (args, /)¶Handle uncaught exception raised by
The args argument has the following attributes:
If exc_type is If this function raises an exception,
Storing exc_value using a custom hook can create a reference cycle. It should be cleared explicitly to break the reference cycle when the exception is no longer needed. Storing thread using a custom hook can resurrect it if it is set to an object which is being finalized. Avoid storing thread after the custom hook completes to avoid resurrecting objects. New in version 3.8. threading. __excepthook__ ¶Holds the original value of New in version 3.10. threading. get_ident ()¶Return the ‘thread identifier’ of the current thread. This is a nonzero integer. Its value has no direct meaning; it is intended as a magic cookie to be used e.g. to index a dictionary of thread-specific data. Thread identifiers may be recycled when a thread exits and another thread is created. New in version 3.3. threading. get_native_id ()¶Return the native integral Thread ID of the current thread assigned by the kernel. This is a non-negative integer. Its value may be used to uniquely identify this particular thread system-wide (until the thread terminates, after which the value may be recycled by the OS). Availability: Windows, FreeBSD, Linux, macOS, OpenBSD, NetBSD, AIX. New in version 3.8. threading. enumerate ()¶Return a list of all threading. main_thread ()¶Return the main New in version 3.4. threading. settrace (func)¶Set a trace function for all threads started from the threading. gettrace ()¶Get the trace function as set by New in version 3.10. threading. setprofile (func)¶Set a profile function for all threads started from the threading. getprofile ()¶Get the profiler function as set by New in version 3.10. threading. stack_size ([size])¶Return the thread stack size used when creating new threads. The optional size argument specifies the stack size to be used for subsequently created threads, and must be 0 (use platform or configured default) or a positive integer value of at least 32,768
(32 KiB). If size is not specified, 0 is used. If changing the thread stack size is unsupported, a Availability: Windows, systems with POSIX threads. This module also defines the following constant: threading. TIMEOUT_MAX ¶The maximum value allowed for the timeout parameter of blocking
functions ( New in version 3.2. This module defines a number of classes, which are detailed in the sections below. The design of this module is loosely based on Java’s threading model. However, where Java makes locks and condition variables basic behavior of every object, they are separate objects in Python. Python’s
All of the methods described below are executed atomically. Thread-Local Data¶Thread-local data is data whose values are thread specific. To manage thread-local data, just create an instance of mydata = threading.local() mydata.x = 1 The instance’s values will be different for separate threads. classthreading. local ¶A class that represents thread-local data. For more details and extensive examples, see the documentation string of the Thread Objects¶The Once a thread object is created,
its activity must be started by calling the thread’s Once the thread’s activity is started, the thread is considered ‘alive’. It stops being alive
when its Other threads can call a thread’s
A thread has a name. The name can be passed to the constructor, and read or changed through the
If the A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread.
The flag can be set through the Note Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling
mechanism such as an There is a “main thread” object; this corresponds to the initial thread of control in the Python program. It is not a daemon thread. There is the possibility that “dummy thread objects” are created. These are thread objects corresponding to “alien threads”, which are threads of control started outside the threading module, such as
directly from C code. Dummy thread objects have limited functionality; they are always considered alive and daemonic, and cannot be threading. Thread (group=None, target=None, name=None, args=(), kwargs={}, *,
daemon=None)¶This constructor should always be called with keyword arguments. Arguments are: group should be target is the callable object to be invoked by the
name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number, or “Thread-N (target)” where “target” is args is the argument tuple
for the target invocation. Defaults to kwargs is a dictionary of keyword arguments for the target invocation. Defaults to If not If the subclass overrides the constructor, it must make sure to invoke the base class constructor ( Changed in version 3.10: Use the target name if name argument is omitted. Changed in version 3.3: Added the daemon argument. start ()¶Start the thread’s activity. It must be called at most once per thread object. It arranges for
the object’s This method will raise a run ()¶Method representing the thread’s activity. You may override this method in a subclass. The standard join (timeout=None)¶Wait until the thread terminates. This
blocks the calling thread until the thread whose When the timeout argument is present and not When the timeout argument is not present or A thread can be
name ¶A string used for identification purposes only. It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor. getName ()¶
setName ()¶Deprecated getter/setter API for Deprecated since version 3.10. ident ¶The ‘thread identifier’ of this thread or native_id ¶The Thread ID ( Note Similar to Process IDs, Thread IDs are only valid (guaranteed unique system-wide) from the time the thread is created until the thread has been terminated. Availability: Requires New in version 3.8. is_alive ()¶Return whether the thread is alive. This method returns daemon ¶A boolean value indicating whether this thread is a daemon thread ( The entire Python program exits when no alive non-daemon threads are left. isDaemon ()¶ setDaemon ()¶
Deprecated getter/setter API for Deprecated since version 3.10. Lock Objects¶A primitive lock is a synchronization primitive that is not owned by a particular thread when locked. In Python, it is currently the lowest level synchronization primitive available, implemented directly by the A primitive lock is in one of two states, “locked” or “unlocked”. It is created in the unlocked state. It has two
basic methods, Locks also support the context management protocol. When more than one thread is blocked in All methods are executed atomically. classthreading. Lock ¶The class implementing primitive lock objects. Once a thread has acquired a lock, subsequent attempts to acquire it block, until it is released; any thread may release it. Note that acquire (blocking=True, timeout=- 1)¶Acquire a lock, blocking or non-blocking. When invoked with the blocking argument set to When invoked with the blocking argument set to When invoked with the floating-point timeout argument set to a positive value, block for at most the number of seconds specified by timeout and as long
as the lock cannot be acquired. A timeout argument of The return value is Changed in version 3.2: The timeout parameter is new. Changed in version 3.2: Lock acquisition can now be interrupted by signals on POSIX if the underlying threading implementation supports it. release ()¶Release a lock. This can be called from any thread, not only the thread which has acquired the lock. When the lock is locked, reset it to unlocked, and return. If any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. When invoked on an unlocked lock, a There is no return value. locked ()¶Return RLock Objects¶A reentrant lock is a synchronization primitive that may be acquired multiple times by the same thread. Internally, it uses the concepts of “owning thread” and “recursion level” in addition to the locked/unlocked state used by primitive locks. In the locked state, some thread owns the lock; in the unlocked state, no thread owns it. To lock the lock, a thread calls its Reentrant locks also support the context management protocol. classthreading. RLock ¶This class implements reentrant lock objects. A reentrant lock must be released by the thread that acquired it. Once a thread has acquired a reentrant lock, the same thread may acquire it again without blocking; the thread must release it once for each time it has acquired it. Note that acquire (blocking=True, timeout=-
1)¶Acquire a lock, blocking or non-blocking. When invoked without arguments: if this thread already owns the lock, increment the recursion level by one, and return immediately. Otherwise, if another thread owns the lock, block until the lock is unlocked. Once the lock is unlocked (not owned by any thread), then grab ownership, set the recursion level to one, and return. If more than one thread is blocked waiting until the lock is unlocked, only one at a time will be able to grab ownership of the lock. There is no return value in this case. When invoked with the blocking argument set to When invoked with the blocking argument set to When invoked with the floating-point timeout argument set to a positive value, block for at most the number of seconds specified by timeout and as long as the lock cannot be acquired. Return Changed in version 3.2: The timeout parameter is new. release ()¶Release a lock, decrementing the recursion level. If after the decrement it is zero, reset the lock to unlocked (not owned by any thread), and if any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. If after the decrement the recursion level is still nonzero, the lock remains locked and owned by the calling thread. Only call this method when the calling thread owns the lock. A There is no return value. Condition Objects¶A condition variable is always associated with some kind of lock; this can be passed in or one will be created by default. Passing one in is useful when several condition variables must share the same lock. The lock is part of the condition object: you don’t have to track it separately. A condition variable obeys the
context management protocol: using the Other methods must be called with the associated lock held. The The Note: the The typical programming style using condition variables uses the lock to synchronize access to some shared state; threads that are interested in a particular change of state call
# Consume one item with cv: while not an_item_is_available(): cv.wait() get_an_available_item() # Produce one item with cv: make_an_item_available() cv.notify() The # Consume an item with cv: cv.wait_for(an_item_is_available) get_an_available_item() To choose between threading. Condition (lock=None)¶This class implements condition variable objects. A condition variable allows one or more threads to wait until they are notified by another thread. If the lock argument is given and not Changed in version 3.3: changed from a factory function to a class. acquire (*args)¶Acquire the underlying lock. This method calls the corresponding method on the underlying lock; the return value is whatever that method returns. release ()¶Release the underlying lock. This method calls the corresponding method on the underlying lock; there is no return value. wait (timeout=None)¶Wait until notified or until a timeout occurs. If the calling thread has not acquired the lock when this method is called, a
This method releases the underlying lock, and then blocks until it is awakened by a When the timeout argument is present and not When the underlying lock is an The return value is Changed in version 3.2: Previously, the method
always returned wait_for (predicate, timeout=None)¶Wait until a condition evaluates to true. predicate should be a callable which result will be interpreted as a boolean value. A timeout may be provided giving the maximum time to wait. This utility method may call Ignoring the timeout feature, calling this method is roughly equivalent to writing: while not predicate(): cv.wait() Therefore, the same rules apply as with New in version 3.2. notify (n=1)¶By default, wake up one thread waiting on this condition, if any. If the calling thread has not acquired the lock when this method is called, a
This method wakes up at most n of the threads waiting for the condition variable; it is a no-op if no threads are waiting. The current implementation wakes up exactly n threads, if at least n threads are waiting. However, it’s not safe to rely on this behavior. A future, optimized implementation may occasionally wake up more than n threads. Note: an awakened thread does not actually return from its notify_all ()¶Wake up all threads waiting on this condition. This method acts like The method Semaphore Objects¶This is one of the oldest synchronization primitives in the history of computer science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he used the names A semaphore manages an internal counter which is decremented by each
Semaphores also support the context management protocol. classthreading. Semaphore (value=1)¶This class implements semaphore objects. A semaphore manages an
atomic counter representing the number of The optional argument gives the initial value for the internal counter; it defaults to Changed in version 3.3: changed from a factory function to a class. acquire (blocking=True,
timeout=None)¶Acquire a semaphore. When invoked without arguments:
When invoked with blocking set to When invoked with a timeout other than Changed in version 3.2: The timeout parameter is new. release (n=1)¶Release a semaphore, incrementing the internal counter by n. When it was zero on entry and other threads are waiting for it to become larger than zero again, wake up n of those threads. Changed in version 3.9: Added the n parameter to release multiple waiting threads at once. classthreading. BoundedSemaphore (value=1)¶Class implementing bounded semaphore objects. A bounded semaphore checks to make sure its current value doesn’t exceed its initial value. If it does,
Changed in version 3.3: changed from a factory function to a class. Semaphore Example¶Semaphores are often used to guard resources with limited capacity, for example, a database server. In any situation where the size of the resource is fixed, you should use a bounded semaphore. Before spawning any worker threads, your main thread would initialize the semaphore: maxconnections = 5 # ... pool_sema = BoundedSemaphore(value=maxconnections) Once spawned, worker threads call the semaphore’s acquire and release methods when they need to connect to the server: with pool_sema: conn = connectdb() try: # ... use connection ... finally: conn.close() The use of a bounded semaphore reduces the chance that a programming error which causes the semaphore to be released more than it’s acquired will go undetected. Event Objects¶This is one of the simplest mechanisms for communication between threads: one thread signals an event and other threads wait for it. An event object manages an internal flag that can be set to true with the threading. Event ¶Class implementing event objects. An event manages a flag that can be set to true with the Changed in version 3.3: changed from a factory function to a class. is_set ()¶Return The method set ()¶Set the internal flag to true. All threads waiting for it to become true are awakened. Threads that call clear ()¶Reset the internal flag to false. Subsequently, threads calling wait (timeout=None)¶Block until the
internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls When the timeout argument is present and not This method returns Changed in version 3.1: Previously, the method always returned Timer Objects¶This class represents an action that should be run only after a certain amount of time has passed — a timer. Timers are started, as with threads, by calling their For example: def hello(): print("hello, world") t = Timer(30.0, hello) t.start() # after 30 seconds, "hello, world" will be printedclass threading. Timer (interval, function, args=None,
kwargs=None)¶Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed. If args is Changed in version 3.3: changed from a factory function to a class. cancel ()¶Stop the timer, and cancel the execution of the timer’s action. This will only work if the timer is still in its waiting stage. Barrier Objects¶New in version 3.2. This class provides a simple synchronization primitive for use by a fixed number of threads that need to wait for each other. Each of the threads tries to pass the barrier by calling the
The barrier can be reused any number of times for the same number of threads. As an example, here is a simple way to synchronize a client and server thread: b = Barrier(2, timeout=5) def server(): start_server() b.wait() while True: connection = accept_connection() process_server_connection(connection) def client(): b.wait() while True: connection = make_connection() process_client_connection(connection)class threading. Barrier (parties, action=None, timeout=None)¶Create a
barrier object for parties number of threads. An action, when provided, is a callable to be called by one of the threads when they are released. timeout is the default timeout value if none is specified for the wait (timeout=None)¶Pass the barrier. When all the threads party to the barrier have called this function, they are all released simultaneously. If a timeout is provided, it is used in preference to any that was supplied to the class constructor. The return value is an integer in the range 0 to parties – 1, different for each thread. This can be used to select a thread to do some special housekeeping, e.g.: i = barrier.wait() if i == 0: # Only one thread needs to print this print("passed the barrier") If an action was provided to the constructor, one of the threads will have called it prior to being released. Should this call raise an error, the barrier is put into the broken state. If the call times out, the barrier is put into the broken state. This method may raise a
reset ()¶Return the barrier to the default,
empty state. Any threads waiting on it will receive the Note that using this function may require some external synchronization if there are other threads whose state is unknown. If a barrier is broken it may be better to just leave it and create a new one. abort ()¶Put the barrier into a broken state. This causes any active or future calls to It may be preferable to simply create the barrier with a sensible timeout value to automatically guard against one of the threads going awry. parties ¶The number of threads required to pass the barrier. n_waiting ¶The number of threads currently waiting in the barrier. broken ¶A boolean that is threading. BrokenBarrierError ¶This exception, a subclass of Using locks, conditions, and semaphores in the with statement¶All of the objects provided by this module that have with some_lock: # do something... is equivalent to: some_lock.acquire() try: # do something... finally: some_lock.release() Currently, What is thread module in Python?The threading module exposes all the methods of the thread module and provides some additional methods − threading. activeCount() − Returns the number of thread objects that are active. threading. currentThread() − Returns the number of thread objects in the caller's thread control.
What is thread in Python with example?What Is a Thread? A thread is a separate flow of execution. This means that your program will have two things happening at once. But for most Python 3 implementations the different threads do not actually execute at the same time: they merely appear to.
Which Python libraries support threads?There are two modules which support the usage of threads in Python:. thread. and.. threading.. What is the use of thread in Python?Threads in python are an entity within a process that can be scheduled for execution. In simpler words, a thread is a computation process that is to be performed by a computer. It is a sequence of such instructions within a program that can be executed independently of other codes.
|