Multithreading in Python: A Complete Guide | FACE Prep

Multithreading in Python: A Complete Guide | FACE Prep

Multithreading in Python | FACE Prep

Multithreading in PythonUnderstanding Multithreading in Python requires knowledge of multitasking. Let’s dive into the concept of multitasking to set the stage.

What is Multitasking?

In simple terms, multitasking is the process of performing multiple tasks simultaneously. In programming, it refers to an operating system’s ability to execute several tasks at the same time.For example:
  • Working on MS Office
  • Listening to music on YouTube
  • Downloading a movie
All these tasks are handled simultaneously by the operating system. Multitasking enhances efficiency and productivity.Types of Multitasking:
  1. Process-based multitasking:
    • Known as multiprocessing, it allows a system to use more than one CPU to execute tasks. It’s resource-intensive but powerful.
    • Multiprocessing can be categorized into:
      • Symmetric multiprocessing
      • Asymmetric multiprocessing
  2. Thread-based multitasking:
    • Known as multithreading, it focuses on threads within a process. Let’s explore this in detail.

What is a Thread?

A thread is a lightweight process. Consider playing a mobile game where you have background music, advertisements, and gameplay running simultaneously. Each of these tasks is a thread.Characteristics of a Thread:
  • Has its own Thread ID, program counter, registers, and stack.
  • Executes independently but shares resources with other threads within the same process.
To see the number of threads running on your system:
  1. Open Task Manager
  2. Navigate to Performance
(Add a screenshot or visual of Task Manager highlighting the Threads section)

Why Do We Need Multithreading?

Multithreading offers several advantages:
  • Efficient Time Management: Threads save time by working concurrently.
  • Performance Improvement: Threads are lightweight compared to processes, reducing overhead.

Achieving Multithreading in Python

Python simplifies multithreading with the threading module. Let’s explore how to implement it.

Example: Without Multithreading

# Class 1
def run(self):
    for i in range(3):
        print("FACE Prep")

# Class 2
def run(self):
    for i in range(3):
        print("Python")

# Main Method
t1 = FACE()
t2 = Python()
t1.run()
t2.run()
Output:
FACE Prep
FACE Prep
FACE Prep
Python
Python
Python
Here, the main thread executes methods sequentially. To achieve parallel execution, we need to use threading.

Example: With Multithreading

from threading import Thread

# Thread 1
class FACE(Thread):
    def run(self):
        for i in range(3):
            print("FACE Prep")

# Thread 2
class Python(Thread):
    def run(self):
        for i in range(3):
            print("Python")

# Main Method
t1 = FACE()
t2 = Python()
t1.start()  # Start Thread 1
t2.start()  # Start Thread 2
Output:
FACE Prep
Python
FACE Prep
Python
FACE Prep
Python

Adding Delays with sleep()

To observe threads clearly, we can introduce delays using the sleep() method from the time module.

Example:

from time import sleep
from threading import Thread

class FACE(Thread):
    def run(self):
        for i in range(3):
            print("FACE Prep")
            sleep(1)

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

t1 = FACE()
t2 = Python()
t1.start()
t2.start()
Output:
FACE Prep
Python
FACE Prep
Python
FACE Prep
Python
Here, threads alternate execution every second, demonstrating concurrent execution.

Ensuring Completion with join()

If you add a print statement at the end of the main thread, it may execute before the threads complete. To prevent this, use join() to wait for thread completion.

Example:

from time import sleep
from threading import Thread

class FACE(Thread):
    def run(self):
        for i in range(3):
            print("FACE Prep")
            sleep(1)

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

t1 = FACE()
t2 = Python()
t1.start()
t2.start()
t1.join()  # Wait for Thread 1 to complete
t2.join()  # Wait for Thread 2 to complete
print("Bye")
Output:
FACE Prep
Python
FACE Prep
Python
FACE Prep
Python
Bye
Using join() ensures that the main thread waits for other threads to finish.

FAQs on Multithreading in Python

1. What is Multithreading in Python?

Multithreading is the process of executing multiple threads concurrently within the same process.

2. How is Multithreading achieved in Python?

Multithreading is achieved using the built-in threading module.

3. How can threads be paused?

Threads can be paused using the sleep() method from the time module.
ConclusionBy understanding and leveraging multithreading in Python, you can improve the performance and efficiency of your applications.Click here to know more our program!Multithreading in Python
c