- Learning Objectives
- Prerequisites
- Introduction
- What is a Thread?
- What is Multithreading?
- Why is Multithreading Required?
- Process vs Thread
- Single Threading vs Multithreading
- Thread Lifecycle
- Python Threading Module
- Internal Working
- Summary
After completing this chapter, you will be able to:
- Understand Threads.
- Understand Multithreading.
- Learn why Multithreading is required.
- Differentiate Process and Thread.
- Compare Single Threading and Multithreading.
- Understand the Thread Lifecycle.
- Learn about Python's
threadingmodule.
Before learning this chapter, you should know:
- Functions
- Classes
- Objects
- Exception Handling
Modern applications often perform multiple tasks at the same time.
Examples include:
- Downloading files while browsing.
- Playing music while editing documents.
- Processing multiple client requests in a web server.
- Chat applications sending and receiving messages simultaneously.
If all these tasks execute one after another,
the application becomes slow and less responsive.
To perform multiple tasks concurrently,
Python provides Multithreading.
A Thread is the smallest unit of execution within a process.
A process may contain one or more threads.
Each thread executes independently,
but threads belonging to the same process share resources such as memory.
A Thread is a lightweight execution path inside a process.
Multithreading is the process of executing multiple threads within a single process.
Multiple threads perform different tasks concurrently,
improving responsiveness and resource utilization.
Multithreading allows a program to perform multiple tasks concurrently using multiple threads.
Suppose a web browser needs to:
- Load a web page.
- Download images.
- Play audio.
- Accept user input.
Without multithreading,
each task waits for the previous one to finish.
With multithreading,
all tasks can make progress concurrently,
making the application more responsive.
Multithreading is used in:
- Web Browsers
- Chat Applications
- Online Games
- Banking Systems
- Web Servers
- Video Streaming Platforms
- File Download Managers
- IDEs (Integrated Development Environments)
| Process | Thread |
|---|---|
| Independent program | Smallest execution unit |
| Own memory space | Shares process memory |
| More memory usage | Less memory usage |
| Costly to create | Faster to create |
| Communication is slower | Communication is faster |
| Single Threading | Multithreading |
|---|---|
| One execution path | Multiple execution paths |
| Executes one task at a time | Executes multiple tasks concurrently |
| Slower for concurrent workloads | More responsive for concurrent workloads |
| Easier to manage | Requires synchronization in some cases |
A thread typically passes through the following states:
New
↓
Runnable
↓
Running
↓
Waiting / Blocked
↓
Runnable
↓
Terminated
- New – Thread object is created.
- Runnable – Thread is ready to execute.
- Running – Thread is executing.
- Waiting / Blocked – Thread waits for a resource or event.
- Terminated – Thread completes execution.
Python provides the built-in
threadingmodule for creating and managing threads.
Example
import threadingCommonly used classes and methods include:
| Component | Purpose |
|---|---|
Thread |
Creates a thread |
start() |
Starts thread execution |
run() |
Defines thread task |
join() |
Waits for a thread to finish |
current_thread() |
Returns the currently executing thread |
active_count() |
Returns the number of active threads |
Program Starts
↓
Main Thread Created
↓
Additional Threads Created
↓
Scheduler Allocates CPU Time
↓
Threads Execute Concurrently
↓
Threads Complete
↓
Program Ends
- Improves responsiveness.
- Better CPU utilization for I/O-bound tasks.
- Allows concurrent task execution.
- Improves user experience.
- Efficient resource sharing.
- Requires synchronization when sharing data.
- Debugging can be more difficult.
- Poor thread management may cause deadlocks or race conditions.
- CPU-bound tasks may not speed up due to Python's Global Interpreter Lock (GIL).
Note: In CPython, the Global Interpreter Lock (GIL) allows only one thread to execute Python bytecode at a time. Multithreading is therefore most beneficial for I/O-bound tasks (such as file operations, network requests, and database access) rather than CPU-intensive computations.
- Create threads only when concurrency is beneficial.
- Keep thread tasks independent whenever possible.
- Synchronize shared resources properly.
- Wait for threads using
join()when required. - Avoid creating unnecessary threads.
Assuming multithreading always improves performance.
For CPU-bound tasks in CPython, the GIL may limit performance gains.
Sharing data without synchronization.
This can lead to inconsistent results.
Creating too many threads.
Too many threads increase memory usage and scheduling overhead.
A Thread is the smallest unit of execution within a process.
Multithreading is the execution of multiple threads concurrently within a single process.
A process has its own memory space, while threads within the same process share memory and resources.
threadingThe Global Interpreter Lock (GIL) is a mechanism in CPython that allows only one thread to execute Python bytecode at a time, making multithreading most effective for I/O-bound tasks.
- Thread → Smallest execution unit
- Multithreading → Multiple threads in one process
- Threads share memory
threadingmodule → Used for thread managementThread,start(),join()- GIL affects CPU-bound multithreading in CPython
In this chapter, we learned:
- Thread
- Multithreading
- Process vs Thread
- Single Threading vs Multithreading
- Thread Lifecycle
- Python
threadingModule - GIL (Introduction)
- Advantages
- Limitations
- Best Practices
- Interview Questions
- Quick Revision
Write a Python program to create a thread using a target function.
import threading
def display():
print("Thread is Running")
thread = threading.Thread(target=display)
thread.start()
thread.join()Thread is Running
- A thread is created using the
Threadclass. - The
targetparameter specifies the function to execute. start()begins thread execution.join()waits for the thread to finish.
import threading
def display():
print("Child Thread")
thread1 = threading.Thread(target=display)
thread2 = threading.Thread(target=display)
thread1.start()
thread2.start()
thread1.join()
thread2.join()Child Thread
Child Thread
Two independent threads execute the same function concurrently.
The execution order may vary.
import threading
class MyThread(threading.Thread):
def run(self):
print("Thread Executing")
thread = MyThread()
thread.start()
thread.join()Thread Executing
Instead of using the target parameter,
the run() method is overridden.
When start() is called,
Python automatically invokes run().
import threading
class MyThread(threading.Thread):
def run(self):
print("Executing Child Thread")
thread1 = MyThread()
thread2 = MyThread()
thread1.start()
thread2.start()
thread1.join()
thread2.join()Executing Child Thread
Executing Child Thread
import threading
def display():
print(threading.current_thread().name)
thread = threading.Thread(target=display)
thread.start()
thread.join()Thread-1
current_thread()
returns the thread currently executing the function.
import threading
print("Active Threads :",
threading.active_count())Active Threads : 1
active_count()
returns the number of currently active threads.
import threading
print(threading.current_thread().name)MainThread
Every Python program begins execution in the
MainThread
import threading
def display(name):
print("Welcome", name)
thread = threading.Thread(
target=display,
args=("Rahul",)
)
thread.start()
thread.join()Welcome Rahul
Arguments are passed to the thread function using the
argsparameter.
import threading
def task1():
print("Downloading File")
def task2():
print("Playing Music")
thread1 = threading.Thread(target=task1)
thread2 = threading.Thread(target=task2)
thread1.start()
thread2.start()
thread1.join()
thread2.join()Downloading File
Playing Music
Two independent tasks execute concurrently.
The output order may differ between executions.
import threading
def display():
print("Child Thread Finished")
thread = threading.Thread(target=display)
thread.start()
thread.join()
print("Main Thread Finished")Child Thread Finished
Main Thread Finished
join() blocks the main thread until the child thread completes.
Without join(), the order of output is not guaranteed.
Program Starts
↓
Main Thread Created
↓
Child Thread Created
↓
start()
↓
Scheduler Executes Thread
↓
Thread Completes
↓
join()
↓
Program Ends
Process
│
├── Main Thread
│
├── Child Thread 1
│
└── Child Thread 2
↓
Shared Memory
↓
Program Ends
- Executes multiple tasks concurrently.
- Improves application responsiveness.
- Efficient for I/O-bound operations.
- Shares process resources efficiently.
- Supports background processing.
- Use the
threadingmodule for thread creation. - Prefer creating threads using target functions unless subclassing is necessary.
- Always call
join()when the main thread depends on child threads. - Minimize shared mutable data between threads.
- Synchronize shared resources when required.
Calling run() directly.
❌ Incorrect
thread.run()This executes the method in the current thread.
✅ Correct
thread.start()start() creates a new thread and then calls run() internally.
Forgetting join().
The main thread may finish before child threads complete.
Assuming thread execution order is fixed.
The operating system scheduler determines execution order.
Creating unnecessary threads.
Too many threads increase scheduling overhead and memory usage.
threadingstart() creates a new thread and internally invokes run().
Calling run() directly executes the method in the current thread without creating a new thread.
join() makes the calling thread wait until the specified thread finishes execution.
It returns the currently executing thread object.
It returns the number of currently active threads.
Yes.
Threads within the same process share memory and resources.
No.
The operating system scheduler determines the execution order.
- Create a thread using a target function.
- Create a thread by extending the
Threadclass. - Display the current thread name.
- Display the number of active threads.
- Execute multiple tasks using multiple threads.
threading.Thread()→ Creates a thread.start()→ Starts execution.run()→ Contains thread logic.join()→ Waits for thread completion.current_thread()→ Returns current thread.active_count()→ Returns active thread count.- Threads share process memory.
In this chapter, we learned:
- Creating Threads
- Target Functions
- Extending the Thread Class
start()run()join()current_thread()active_count()- Practical Programs
- Best Practices
- Common Mistakes
- Interview Questions
- Practice Programs
- Quick Revision