Categories: python

threading Module In Python

Python threading, as we saw in the previous tutorial, allows us to run different parts of our program concurrently, which can simplify our design.

Functions of threading Module:

Following are some of the Functions:

FunctionDescription
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.

threading Module Objects:

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:

ObjectDescription
ThreadIt is an object that represents a single thread of execution.
LockPrimitive lock object.
RLockThe RLock or Re-entrant lock object allows a single thread to (re)acquire an already-held lock (recursive locking).
ConditionA 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)
EventIt’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.
SemaphoreWhen no resources are available, it provides a “counter” of finite resources shared between threads.
BoundedSemaphoreSimilar to a Semaphore, but ensures that the initial value is never exceeded.
TimerThread-like, except it waits for a specified amount of time before running.
BarrierCreates 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.

Example:
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.

Output:
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

Follow Me

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

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago