Python

Python Multithreading

“Within a process, an execution unit is known as a thread. By swiftly moving the CPU’s attention between threads, numerous threads can be run simultaneously in a process known as multithreading (also called context switching). The basics of Python multithreading will be covered in this article. For your help, we will also provide a variety of examples.”

Multithreading in Python

Multithreading is a threading technique used in Python programming to run many threads at the same time.  Additionally, it enables sharing of its data space with the primary threads inside a process, which communicate and share information more easily than separate processes. The goal of multithreading is to carry out numerous processes concurrently, which improves the application’s rendering and performance.

It is a very practical method for speeding up and enhancing the functionality of an application. By using multithreading, a programmer can break down application duties into smaller jobs and run multiple instances of the program at once. It enables threads to communicate with one another and share processor resources, including memory, files, and data. Additionally, it makes users more willing to keep using a program even when a section of it is blocked or too long.

Example 1

Here is a simple Python program for multithreading. Let’s look at a Python program that has two classes, “Python_demo” and “Python_lesson.” let’s look into this sample code in detail.

Two of our classes use similar techniques. The output of the run function of the first class’s object when it is constructed and printed the phrase “Python Demo” four times. The word “Python Lesson” appears four times when we repeat the process for the second class.

class Python_demo:
    def run(self):
        for i in range(4):
            print("Python Demo")
class Python_lesson:
    def run(self):
        for i in range(4):
            print("Python Lesson")
first_obj = Python_demo()
second_obj = Python_lesson()
first_obj.run()
second_obj.run()

The outcome if we run this program is as follows. Python Demo and Python Lesson are shown four times in succession, as you can see. As a result, the main thread is where this program runs. Every program contains the main thread. In this instance, both operations are carried out in a sequence.

Example 2

We’ll employ Python’s threading module as an example. We might understand the necessity of multithreading if we consider the first scenario. That implies that both procedures must be used simultaneously. Python’s Thread class and threading package can be used to achieve this. Let’s try to think of something. Now that multithreading is present, the sample program has been updated. Additionally, each class was run as its own thread using the Thread class.

We also made a difference by not directly calling the run method. Instead, we make use of the start method, which is basically the threading implementation mechanism.

When we apply the start method, the run function is instantly called in the background. We currently execute the main thread by default. Two child threads, first obj, and second obj, are formed when the start methods are called.

from threading import *
class Python_demo(Thread):
    def run(self):
        for i in range(4):
            print("Python Demo")
class Python_lesson(Thread):
    def run(self):
        for i in range(4):
            print("Python Lesson")
first_obj = Python_demo()
second_obj = Python_lesson()
first_obj.start()
second_obj.start()

These adjustments result in the output that is displayed below. Now that the application is running, multithreading can be seen to be happening. We can see that several words are clustered together, despite the fact that “Python Demo” and “Python Lesson” are two separate phrases. This resulted from a collision. It happens as a result of two threads (first_obj and second_obj) trying to execute on the CPU concurrently due to the processor’s excessive speed.

Example 3

Schedulers in the operating system specify the time for execution. In this example, the instructions are carried out by the software more than once at a specific time.

We can prevent this by using the sleep approach to provide a small delay to our software. To accomplish this, we must import the sleep function from the time module to add a brief pause between the two threads’ execution. Except for the addition of the sleep function, the code is virtually identical to the examples from before.

Notice the necessary modules, threading, and sleep. These modules are imported first. The sleep function is then executed in two classes that are later constructed. In order to print the sentence a certain number of times—in our case, three—we have utilized the for loop in both classes. In order to run the application, we invoked the start() method after implementing the threading approach. The program’s final lines of code demonstrate this.

from threading import *
from time import sleep
class Python_demo(Thread):
    def run(self):
        for i in range(3):
            print("Python Demo")
            sleep(1)
class Python_lesson(Thread):
    def run(self):
        for i in range(3):
            print("Python Lesson")
            sleep(1)
first_obj = Python_demo()
second_obj = Python_lesson()
first_obj.start()
sleep(0.3)
second_obj.start()

The result now demonstrates that the threads are running simultaneously.

Example 4

The threading module in Python is used to construct threads in the following code snippet. The main thread runs in the code, and the words “This is the main thread” are printed. The first thread and second thread are two newly established and running threads. There is a context transition, and the first thread begins to run.

The first thread goes to sleep after the first four iterations, while the second thread begins working and completes just in time for the next context switch.

The CPU is now under the control of the main thread, which writes “Main thread again!”

The second thread resumes its execution after another context switch and completes. The main thread can no longer execute any more instructions; hence the program ends.

import threading as td
import time as t
def print_Welcome():
  for i in range(5):
    if i == 4:
      t.sleep(2)
    print("Welcome")
def print_integers(n):
  for i in range(n+1):
    print(i)
print("This is the main thread.")
first_thread = td.Thread(target = print_Welcome, args = ())
second_thread = td.Thread(target = print_integers, args = (10,))  
first_thread.start()
second_thread.start()
print("Main thread again!")

You can see the output in this section, where the main thread executes first, and the message is repeated as needed. Following the execution of the second thread, which displayed the numbers, the software returned to the first thread and carried out the function that shows the word “Welcome.”

Conclusion

The topic of this article was Python multithreading. By swiftly switching between threads using a CPU, multithreading is a threading technique used in Python programming to run many threads simultaneously. Additionally, it enables sharing of its data space with the primary threads inside a process, which communicate and share information more easily than separate processes. The goal of multithreading is to carry out numerous processes concurrently.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content