Implementing Threading without inheriting the Thread Class in Python
We are going implement threading in Python using a Class without sub-classing the superclass called Thread.
To make the best use of the underlying processor and to improve the performance of our application, we can create multiple threads that can execute in parallel. Making the best use of the processor and also our application will give the best user experience, it will be fast.
There are three ways to create threads in Python:
- Using a function
- Extending thread class
- Without extending thread class
We will implement the last approach is also called the hybrid approach. We will define a Class but the Class will not extend the parent class thread instead we are going to directly define any function inside that we want. Instead, we will create an instance of the thread and then pass the object and the function which we want to execute within that object as the target and the argument is the second argument. Then invoke the Thread start method.
Implementing Thread by printing the first 10 natural numbers
Thread-1 0 1 2 3 4 5 6 7 8 9 10
Implementing Thread by printing even numbers within a given range
Thread-1 10 12 14 16 18 20