Thread-based Parallelism in Python
A thread is a group of commands in computer science that can be controlled separately by a scheduler, a part of the operating system.
The thread is used to run multiple threads simultaneously. A thread means multiple tasks and function calls in the program. A multi-threaded program has sub-programs that are managed by an individual thread. Parallelism in software execution is made possible via multi-threading. The active threads run simultaneously and share the CPU resources resulting in fast execution of the program.
Uses of Multi-threading
Threading Module in Python
Python provides a powerful module named threading that supports different threads.
It gives various functions for obtaining the threads and their related data. Moreover, these functions are automatically executed. These functions and methods are
Importing Threading Module in Python
Let's implement the threading concept in Python.
Creating a new thread
The threading module is used to create new threads. The data in the new thread created is initialized with the help of the __init__ function. The run function defines the thread's behavior after the execution of the new thread starts.
We must follow these steps to create a new thread:
Program 1: Program to create a new thread in Python.
Creating new threads JTP 2300 Javatpoint 5000 Exit
In this, firstly, we have imported the threading module. Then, we made a class named new_thread, and then, using the __init__ function, we initialized the threading class. Then, using the run() function, we defined the thread function. Then we made two thread objects with their IDs. Then, we will start the thread creation; it will print the thread name and ID.
Program 2: Program to illustrate the thread and its functions in Python.
Name of the main thread : MainThread Identity of the main thread : 10528 Stack size is : 0 Passing the trace function None Set the profile of thread: MainThread 1500 Total Number of active threads: 7 Name of the current thread: Thread-19 2900 Total Number of active threads: 7 Name of the current thread: Thread-20 Enumeration list : [<_MainThread(MainThread, started 10528)>,
We first imported the threading module. Then, we called two functions for the trace function and set the profile of the threads. Then we made a thread class then initialized the data of the thread. Then we have to print the details of the thread, like its name, identity, and enumeration list.