Python Multithreading

Multiple tasks may need to be performed by a single process. These many tasks are separate operations that belong to the same process. These independent tasks can be called threads.

An independent execution flow within a process is known as a thread. Multiple threads may be present in a single process. A process that is lightweight is sometimes known as a thread. We can create parallelism by dividing a process up into several threads.

The smallest group of computer instructions that can be independently handled by an operating system scheduler is known as a thread.
Each thread in a process performs out a particular function.

In Python, threading module used to perform threads. To import the threading module, you can use either of the following commands.

import threading
from threading import *

Example : Without thread

class A():
    def run(self):
        for i in range(3):
            print("class A")

class B():
    def run(self):
        for i in range(3):
            print("class B")


if __name__ == "__main__":
    obj1 = A()
    obj2 = B()

    obj1.run()
    obj2.run()
Output:
class A
class A
class A
class B
class B
class B

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.

Example : With Thread

import threading

class A(threading.Thread):
    def run(self):
        for i in range(3):
            print("class A")

class B(threading.Thread):
    def run(self):
        for i in range(3):
            print("class B")

if __name__ == "__main__":
    obj1 = A()
    obj2 = B()

    obj1.start()
    obj2.start()

The example programme has now been changed to include multithreading. The threading module was imported. Additionally, we used the Thread class for both classes to enable threaded operation.

The other adjustment we made was to avoid directly calling the run method. Instead, we made use of the start method, which is the method we apply when developing threading.

The run method is automatically called in the background when the start method is called.

Right now, the default thread is the main thread. Two child threads, thread1 and thread2, will be created when we invoke the start methods. These two threads will both be active at the same time.

Output:
class A
class A
class B
class A
class B
class B

You can see in this output these two thread does not run in a order. In first two line was executed by class A but we need to execute these two threads simultaneously.

This occurred due to a collision. It is due to the processor’s excessive speed that two threads come at the CPU for execution at the same time.

Schedulers are a feature of the operating system that will specify the time for execution. In this illustration, the programme is running the commands more than once at one specific moment in time.
By using the sleep approach, we may prevent this by putting a tiny delay to our software. To create a slight delay between the execution of the two threads, we must import the sleep method from the time module.

Example : Thread with sleep()

import threading
from time import sleep

class A(threading.Thread):
    def run(self):
        for i in range(3):
            print("class A")
            sleep(1)

class B(threading.Thread):
    def run(self):
        for i in range(3):
            print("class B")
            sleep(1)



if __name__ == "__main__":
    obj1 = A()
    obj2 = B()

    obj1.start()
    sleep(0.3)
    obj2.start()
Output : 
class A
class B
class A
class B
class A
class B

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.

That is it for today, hope it helps. If you have any suggestion for this article
please make a comment in comment section below.

If you like this article, you can buy me a coffee. Thanks!

Python Multithreading

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top