The other day, I was watching a video about Java programming, and in that video, the instructor was talking about multithreading. Then, I was wondering whether multithreading is possible in Python or not.
I have done some research on this topic and I just want to share what I have learned.
Is Python multithreaded? Yes. Python programming language supports multithreading. We can do multithreading in Python by importing the module called ‘threading’ and using the class ‘Thread’.
If you want to know how multithreading works in Python, just stay around. But before discussing that, we need to take a look at some important terms related to multithreading.
To understand what is multithreading, we must first take a look at what is multitasking.
What is Multitasking?
In computing, multitasking is the execution of multiple tasks at the same time over a certain period. Modern operating systems permit users to run several applications or software at the same time.
Nowadays, we all have machines that have CPUs with multiple cores. So, multiple tasks can be run at the same time.
Some tasks can run in the background while the users do some other work in the foreground.
For example, you can download some files from the Internet while listening to music in your system and concurrently playing a game. In this, multiple tasks take place simultaneously and this can be considered as multitasking.
Generally, we can divide multitasking into two different categories. Multitasking can either be process-based(multiprocessing) or thread-based(multithreading).
What is Multiprocessing?
Multiprocessing is two or more processes functioning concurrently on the same operating system. In this case, the smallest unit can be called a process.
It can also be stated as the ability of a system to support more than one processor or the ability to allocate tasks between them.
The previous example that I have mentioned above is a type of multiprocessing.
In that, downloading a file is a separate process, playing music is a separate process and playing games is another separate process. All these processes take place simultaneously.
What is Multithreading?
A single process may have separate tasks to be achieved. All of these tasks are independent parts of the same process. These independent tasks can be called threads.
A thread is an independent flow of execution within a process. A single process can contain multiple threads. A thread is also known as a lightweight process. By dividing a process into multiple threads, we can achieve parallelism.
A thread is the smallest sequence of programmed instructions that can be managed independently by a scheduler of the operating system.
Each thread in a process performs a particular task. For example, take the case of playing the Pro Evolution Soccer(PES) game.
This game is a single process and it further consists of several tasks such as moving the ball, changing the direction, playing music, etc., that can be worked simultaneously. We have so many things happening at the same time.
Multithreading is the ability of a CPU to provide multiple threads of execution concurrently, supported by the operating system.
Multithreading is very helpful in saving time as well as improving performance. However, it can not be applied in every situation.
Multithreading can be used only when multiple tasks need to be achieved, that do not have interdependency.
Multithreading in Python
Let’s see how we can do multithreading in the Python programming language.
To achieve multithreading in Python, we need to import the threading module. Now, before importing this module, you have to install it on your Python environment.
Fortunately, the threading module is already there in Python’s standard library. You don’t need to install it manually on your system. If you have Python installed on your system, you are ready to go.
To import the threading module, you can use either of the following commands.
from threading import *
That is how we import the threading module.
An Example for Multithreading in Python
Now, let us see how to create multiple threads with Python and implement multithreading.
Before that, let’s see a Python program with two classes, namely ‘Pythonista’ and ‘Planet’.
class Pythonista: def run(self): for i in range(3): print("Pythonista") class Planet: def run(self): for i in range(3): print("Planet") obj1 = Pythonista() obj2 = Planet() obj1.run() obj2.run()
Take a look at this program. We have two classes with similar methods. In the first class, when we create the object and call the run method, it prints ‘Pythonista’ three times.
When we do the same for the second class, it prints ‘Planet’ three times.
If we run this program, the output will be like this.
So, this program works in the main thread. Every program has a main thread. Here, it runs both methods one by one.
But, we need to do multithreading. That means, we need to run both methods simultaneously. We can do this by using the threading module and Thread class of Python.
Let’s see how we can do that.
from threading import * class Pythonista(Thread): def run(self): for i in range(3): print("Pythonista") class Planet(Thread): def run(self): for i in range(3): print("Planet") obj1 = Pythonista() obj2 = Planet() obj1.start() obj2.start()
Now, we modified the example program to implement multithreading. We imported the threading module. Also, we used the Thread class for both the classes, so that they can run as individual threads.
The other change we made is that, we did not call the run method directly. Instead, we used the start method, which is the method that we use while implementing threading.
When we call the start method, it will automatically invoke the run method in the background.
Now, we have the main thread by default. When we call the start methods, it will create two child threads say thread1 and thread2. Both these threads will run at the same time.
After doing these modifications, we get the output as given below.
Now, we can see that multithreading was done while executing the program.
We can see that some words are placed together, like ‘PythonistaPlanet’ even though they are separate words ‘Pythonista’ and ‘Planet’.
This occurred due to a collision. It is because the processor is too fast and two threads are coming to the CPU for execution at the same instance of time.
The operating system has something called schedulers which will specify the time for execution. In this example, the program is executing the instructions more than once at one particular instance of time.
We can avoid this by adding a small delay to our program by using the sleep method. For this, we need to import the sleep method from the time module to add a little bit of delay between the execution of the two threads.
from threading import * from time import sleep class Pythonista(Thread): def run(self): for i in range(3): print("Pythonista") sleep(1) class Planet(Thread): def run(self): for i in range(3): print("Planet") sleep(1) obj1 = Pythonista() obj2 = Planet() obj1.start() sleep(0.3) obj2.start()
Now, we can see that the threads execute simultaneously and it is very evident in the output.
This is how we do multithreading in the Python programming language.
If you have any doubts or queries regarding this article, feel free to ask them in the comments section.
You can check out this tutorial to learn more about the fundamental concepts of Python.
If this article was helpful to you, do share it with your friends.