Python threading, as we saw in the previous tutorial, allows us to run different parts of our program concurrently, which can simplify our design.
Following are some of the Functions:
Function | Description |
active_count() | Return the number of active Thread objects. The count returned is the same as the length of the list returned by enumerate (). |
current_thread() | Return the current Thread object, which corresponds to the caller’s control thread. |
get_ident() | Return the current thread’s ‘thread identifier’. This is a positive integer. Its value has no direct meaning; it is intended to be used as a magic cookie to index a dictionary of thread-specific data |
get_native_id() | Return the native integral Thread ID assigned by the kernel to the current thread. This is a positive integer. Its value can be used to uniquely identify this thread throughout the system (until the thread terminates, after which the OS may recycle the value). |
enumerate() | Return a list of all active Thread objects. Daemonic threads and dummy thread objects created by current thread are included in the list (). It excludes threads that have been terminated and threads that have not yet been started. |
main_thread() | The main Thread object is returned. Under normal circumstances, the main thread is the one from which the Python interpreter was launched. |
stack_size([size]) | This method returns the size of the thread stack used when creating new threads. The size argument is optional and can be used to set the stack size that will be used to create subsequent threads. It must be 0 or a positive integer (D=the default value is 0). A RuntimeError is thrown if changing the thread stack size is not supported. A ValueError is thrown if the specified stack size is invalid. |
settrace(func) | This method is used to configure a trace function/hook for all threads launched by the threading module. For each thread, the trace function is passed to the sys.settrace() method, which is attached to the thread before the run() method is called. |
setprofile(func) | Configure a profile function for all threads launched by the threading module. For each thread, the func will be passed to sys.setprofile() before the run() method is called. |
This module also defines the following constant: threading.TIMEOUT_MAX
It is the maximum value allowed for the timeout parameter of blocking functions (Lock.acquire(), RLock.acquire(), Condition.wait(), etc.). Specifying a timeout greater than this value will raise an OverflowError.
Aside from the functions listed above, the threading module includes a number of classes whose objects are extremely useful in creating and managing threads.
Following are some of the Object types:
Object | Description |
---|---|
Thread | It is an object that represents a single thread of execution. |
Lock | Primitive lock object. |
RLock | The RLock or Re-entrant lock object allows a single thread to (re)acquire an already-held lock (recursive locking). |
Condition | A condition variable object causes one thread to wait until another thread fulfills a specific “condition” (such as a change in state or some data value) |
Event | It’s a more general version of condition variables in which a number of threads can be made to wait for an event to occur, and all the threads that are waiting will only awaken when the event occurs. |
Semaphore | When no resources are available, it provides a “counter” of finite resources shared between threads. |
BoundedSemaphore | Similar to a Semaphore, but ensures that the initial value is never exceeded. |
Timer | Thread-like, except it waits for a specified amount of time before running. |
Barrier | Creates a “barrier” at which a specified number of threads must all arrive before proceeding. |
Let us take a look at some of the examples for better understanding.
import time
import threading
def thread1(a):
time.sleep(3)
#print('No. printed by Thread 1: %d' %a)
def thread2(a):
time.sleep(3)
#print('No. printed by Thread 2: %d' %a)
if __name__ == '__main__':
th1 = threading.Thread(target=thread1, args=(11,))
th2 = threading.Thread(target=thread2, args=(14,))
th1.start()
th2.start()
print("No. of active threads: " + threading.active_count())
print("Current thread is: " + threading.current_thread())
th1.join()
th2.join()
Here, we have used the active_count() as well as the current_thread() method to get the number of active threads and the current Thread objects.
No. of active threads: 3
Current thread is: <_MainThread(MainThread, started 16134)>
Note: The number of threads is three because we created two threads and the entire execution is taking place in the main thread.
Note: also read about Multithreading In Python
Please follow me to read my latest post on programming and technology if you like my post.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…