Skip to main content

Python Multithreading: Complete Guide with Examples

 

✍️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, allowing
tasks 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 concurrently


Output:
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 thread


Output:
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:


import threading # Imports the threading module for multithreading support def display(name): # Defines a function that accepts an argument print("Hello", name) # Prints a message using the passed argument t = threading.Thread( # Creates a thread object target=display, # Specifies the function to run in the thread args=("Python",) # Passes arguments to the function (tuple required) ) t.start() # Starts the thread execution


Output:
Hello Python

"Code executed successfully" 

Thread Using Class:

Creating a thread using a class allows developers to define custom thread behavior by extending the Thread class.

This approach is useful for complex threading tasks where multiple methods or additional data need to be managed inside a thread.
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() method

Output:
Thread running

"Code executed successfully" 


join() Method:

The 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



Output:
Thread started Thread started Thread finished Thread finished Main program finished

"Code executed successfully" 


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 name


Output:
Current Thread: Thread-1 (task) Current Thread: Thread-2 (task) Main Thread: MainThread

"Code executed successfully" 


Daemon Thread:

A daemon thread is a background thread that runs alongside the main program.
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.

Example:

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 automatically

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 that
must complete before the program exits.


Multithreading vs Multiprocessing:

 Feature                Multithreading               Multiprocessing     
Memory  SharedSeparate
Speed                   Faster (I/O)Faster (CPU)
GILAffectedNot affected
Use caseI/O tasksCPU 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 concurrently


Output:
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() and start()

  • 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.



3️⃣ When to use multithreading?

Ans:
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



Comments

popular

What Is Python Programming? Features, Uses and Career Scope.

  ✍️ Introduction Python is one of the most popular and beginner-friendly programming languages in the world today. It is widely used for web development, data science, artificial intelligence, automation, and software development. Because of its simple syntax and powerful features, Python is an excellent choice for students, beginners, and professionals. In this article, you will learn what Python programming is, its key features, real-life uses, and the career opportunities it offers. 🧠 What Is Python Programming? Python is a high-level, interpreted programming language created to make coding easy and readable. It allows developers to write programs using simple English-like statements, which makes it ideal for beginners. Python supports multiple programming styles such as procedural, object-oriented, and functional programming. ⭐ Features of Python Easy to learn and understand Simple and readable syntax Interpreted language Platform independent Large standard l...

what is Python Date and Time ? Complete Guide with Examples:

  ✍️ Introduction Python provides powerful tools to work with dates and times . The most commonly used module is datetime . The datetime module allows Python programs to create, manipulate, format, and perform calculations with dates and times easily. Date and time handling is used in: Logging systems Attendance & billing systems Data analysis Real-time applications How To Import Date and Time Module : In Python, the datetime module is used to work with dates , times , and date–time combinations . It is part of Python’s standard library, so no installation is required. You can import it in different ways depending on your need. import datetime Get Current Date and Time: This code obtains the current system date and time as a single datetime object using the datetime module. Example: import datetime now = datetime.datetime.now() print (now) Output: 2026-02-13 11:25:53.445827 "Code executed successfully"  Get Only Date: This code retrieves t...

Features of Python Programming Language Explained with Examples

✍️ Introduction Python is one of the most popular programming languages because of its powerful and easy-to-use features. It is designed to make programming simple, readable, and efficient. Python is widely used by beginners as well as professionals due to its flexibility and strong community support. In this article, we will discuss the main features of Python programming language in simple English with easy examples. 🧠 What Are Features of Python? Features of Python are the special characteristics that make it different from other programming languages. These features help programmers write clean, readable, and efficient code with less effort. ⭐ Key Features of Python Programming Language 1️⃣ Easy to Learn and Easy to Use Python has a simple syntax that is close to the English language. This makes it very easy for beginners to learn and understand programming concepts. Example: print("Hello, World!") 2️⃣ Interpreted Language Python is an interpreted language, which me...

Python Operators: Types with Examples

 ✍️Introduction In Python, operators are symbols used to perform operations on variables and values. Operators help us do calculations, comparisons, and logical decisions in programs. In this article, you will learn: • What Python operators are • Types of Python operators • Simple examples for each type