✍️Introduction
Multithreading allows a program to run multiple tasks at the same time.
In Python, multithreading is used to improve performance and responsiveness, especially in I/O-based programs.
Multithreading works by dividing a program into smaller threads that execute concurrently within the same process.
It is especially useful for tasks like file handling, network requests, and user interaction where programs often wait for input or output operations to complete.
What is a Thread?
A thread is a small unit of a process.
A program can have multiple threads running simultaneously.
Threads share the same memory space of a process, which makes communication between them faster.
Each thread executes independently, allowing better utilization of CPU time and improved application responsiveness.
Why Use Multithreading?
-
Faster execution
-
Better CPU utilization
-
Responsive applications
-
Used in real-time systems
Multithreading in Python:
Python provides the threading module to work with threads.
Multithreading in Python is the technique of executing multiple threads concurrently within a single program using the threading module.
The threading module allows developers to create, start, and manage multiple threads within a single program.
It helps in running tasks concurrently, improving performance for I/O-bound operations and keeping applications responsive.
Import Threading Module:
import threading
The threading module is imported to create and manage threads in a Python program.
It provides tools to start, control, and synchronize multiple threads, allowingtasks to run concurrently within the same process.
Create a Thread Using Function:
This program demonstrates how to create and start a thread in Python using a function.
Example:
import threading # Imports the threading module to work with threads def show(): # Defines a function that will run in a separate thread print("Hello from thread") # Code executed by the thread t1 = threading.Thread(target=show) # Creates a thread object and assigns the function to it t1.start() # Starts the thread and runs the function concurrentlyOutput:Hello from thread"Code executed successfully"
Create Multiple Threads:
This program shows how to create and run multiple threads in Python to execute tasks concurrently.
Example:
import threading # Imports the threading module for multithreading support def task(): # Defines the function to be executed by each thread print("Task executed") # Task performed by the thread t1 = threading.Thread(target=task) # Creates the first thread object t2 = threading.Thread(target=task) # Creates the second thread object t1.start() # Starts the first thread t2.start() # Starts the second threadOutput:Task executed Task executed"Code executed successfully"
Thread with Arguments:
A thread with arguments allows data to be passed to the function executed by the thread.
Passing arguments to threads makes them more flexible, as the same function can perform different tasks based on the input values. This is useful when multiple threads need to work on different data simultaneously.
Example:
Thread Using Class:
Thread class.By overriding the
run() method, the code inside it is executed when the thread starts.Example:
import threading # Imports the threading module class MyThread(threading.Thread): # Creates a custom thread class by inheriting Thread def run(self): # Overrides the run() method print("Thread running") # Code executed when the thread starts t = MyThread() # Creates an object of the custom thread class t.start() # Starts the thread and calls the run() methodOutput:Thread running"Code executed successfully"
join() Method:
join() method is used to pause the execution of the main program until a thread completes its task.When
t1.join() or t2.join() is called, the main thread waits for the respective thread to finish execution, ensuring proper synchronization and preventing the program from ending before threads complete.Example:
import threading # Imports threading module for multithreading
import time # Imports time module to use sleep()
def task(): # Defines a function to be executed by threads
print("Thread started") # Indicates thread execution start
time.sleep(2) # Pauses the thread for 2 seconds
print("Thread finished") # Indicates thread execution end
t1 = threading.Thread(target=task) # Creates first thread
t2 = threading.Thread(target=task) # Creates second thread
t1.start() # Starts first thread
t2.start() # Starts second thread
t1.join() # Main program waits until t1 completes
t2.join() # Main program waits until t2 completes
print("Main program finished") # Executes after both threads finish
Current Thread Name:
threading.current_thread().name is used to get the name of the thread that is currently executing the code.By default, the main thread is named "MainThread", and other threads are given automatic names like "Thread-1", "Thread-2", etc.
This is useful for debugging and tracking which thread is running at a particular time.
Example:
import threading # Imports threading module def task(): # Function executed by a thread print("Current Thread:", threading.current_thread().name) # Prints the name of the running thread t1 = threading.Thread(target=task) # Creates a new thread t2 = threading.Thread(target=task) # Creates another new thread t1.start() # Starts first thread t2.start() # Starts second thread print("Main Thread:", threading.current_thread().name) # Prints the main thread nameOutput:Current Thread: Thread-1 (task) Current Thread: Thread-2 (task) Main Thread: MainThread"Code executed successfully"
Daemon Thread:
Daemon threads automatically stop when the main program ends, so they are mainly used for background tasks like logging, monitoring, or cleanup operations
Daemon threads run in background.
import threading # Imports threading module import time # Imports time module def task(): # Function to run as a daemon thread while True: # Infinite loop to simulate background work print("Daemon thread running...") time.sleep(1) # Pauses execution for 1 second t = threading.Thread( # Creates a thread object target=task, # Function executed by the thread daemon=True # Marks the thread as a daemon thread ) t.start() # Starts the daemon thread time.sleep(3) # Main thread runs for 3 seconds print("Main program finished") # When main program ends, daemon thread stops automaticallyExample:
Output:Daemon thread running... Daemon thread running... Daemon thread running... Main program finished"Code executed successfully"Key Point:
Daemon threads are useful for background services but should not be used for tasks thatmust complete before the program exits.
Multithreading vs Multiprocessing:
| Feature | Multithreading | Multiprocessing |
|---|---|---|
| Memory | Shared | Separate |
| Speed | Faster (I/O) | Faster (CPU) |
| GIL | Affected | Not affected |
| Use case | I/O tasks | CPU tasks |
GIL (Global Interpreter Lock):
The Global Interpreter Lock (GIL) is a mechanism in Python that allows only one thread to execute Python bytecode at a time, even on multi-core processors.
This means true parallel execution of CPU-intensive tasks is not possible using threads alone in standard Python.
Because of the GIL:
-
CPU-bound tasks (heavy calculations) do not get performance benefits from multithreading.
-
I/O-bound tasks (file handling, network requests, waiting for input/output) work efficiently, because threads can run while others wait for I/O operations.
Multithreading in Python is best suited for I/O-bound tasks, while multiprocessing is preferred for CPU-heavy tasks.
Real-Life Example: Simulating a Download Using Multithreading
import threading # Imports threading module for multithreading import time # Imports time module to use sleep() def download(): # Defines a function to simulate a download task print("Downloading...") # Displays download start message time.sleep(2) # Pauses execution to simulate download time print("Download complete") # Displays download completion message t = threading.Thread(target=download) # Creates a thread to run the download function t.start() # Starts the thread and runs the function concurrentlyOutput:Downloading... Download complete"Code executed successfully"This program uses a thread to perform a download task in the background while the main program continues running.
❌ Common Mistakes:
-
Forgetting
start() -
Confusing
run()andstart() -
Overusing threads
Multithreading Interview Questions?
1️⃣ What is GIL?
Ans:
The Global Interpreter Lock (GIL) is a Python mechanism that allows only one thread to execute Python code at a time, mainly to ensure memory safety.
2️⃣ Difference between thread and process:
Ans:
A thread is a lightweight unit that shares memory within a process, while a process is an independent program with its own memory space.
Multithreading is best used for I/O-bound tasks such as file handling, network operations, and tasks that require waiting for input or output.
Conclusion:
Python multithreading helps improve application performance and responsiveness.
It is widely used in networking, file handling, and GUI applications.
💬 Quick Question
What happens if we call run() instead of start()?
Comment your answer 👇😊
📌 Related Articles
- Get link
- X
- Other Apps
Labels
Multithreading- Get link
- X
- Other Apps
Comments
Post a Comment