In this Tutorial -:

Multithreading is a powerful concept in Python that allows you to execute multiple threads concurrently, enabling your program to perform multiple tasks simultaneously. It is especially useful when dealing with tasks that involve waiting for I/O operations, such as reading from files or making network requests, as it can significantly improve the overall performance of your application. In this tutorial, we’ll delve into the world of Python multithreading, exploring the basics, benefits, and practical code examples to help you grasp the concept effectively.
Introduction to Multithreading
Multithreading is a technique that allows you to create multiple threads within a single process. Each thread runs independently, performing its tasks simultaneously with other threads. This concurrency enables your program to make better use of multi-core processors, leading to improved performance and responsiveness.
Threading Module in Python
Python provides the threading module, which offers a high-level interface to manage threads. The threading module allows you to create, control, and synchronize threads effortlessly.
Basic Thread Methods
In Python’s threading module, threads are instances of the Thread class. The Thread class provides several methods that allow you to manage threads effectively. Here are some of the basic thread methods in Python:
start(): This method starts the thread’s activity. It invokes the run() method, which you can override in your subclass to define the thread’s behavior.
run(): This method is called when you call the start() method. It represents the entry point for the thread’s activity. You can override this method in your subclass to define what the thread should do.
join(timeout=None): This method blocks the calling thread until the thread on which it is called has finished executing. The timeout argument specifies the maximum time (in seconds) to wait for the thread to finish. If the thread completes within the timeout period, join() returns None. If the thread does not finish within the timeout period, join() returns regardless, and the thread continues running in the background.
is_alive(): This method checks if the thread is still alive (i.e., if it is currently running or has not yet started or has finished executing). It returns True if the thread is alive, and False otherwise.
name: This attribute holds the name of the thread. By default, threads are assigned names like “Thread-1”, “Thread-2”, etc. You can set a custom name using the name attribute.
ident: This attribute holds a unique identifier for the thread. It is an integer value that uniquely identifies the thread.
daemon: This attribute determines if the thread is a daemon thread or not. Daemon threads are background threads that run as long as any non-daemon threads are running. When all non-daemon threads have exited, the interpreter exits, and the daemon threads are abruptly terminated.
These are some of the basic thread methods and attributes available in Python’s Thread class. Understanding these methods is essential for managing threads and coordinating their execution effectively in your multithreading applications.
Creating Threads
You can create a thread in Python by subclassing the Thread class from the threading module or by using the Thread constructor directly. Here’s an example of both approaches:
import threading
# Approach 1: Subclassing Thread class
class MyThread(threading.Thread):
def run(self):
print("Thread is running!")
# Approach 2: Using Thread constructor
def thread_function():
print("Thread function is running!")
my_thread = MyThread()
another_thread = threading.Thread(target=thread_function)
my_thread.start()
another_thread.start()
my_thread.join()
another_thread.join()
O/P
Thread function is running!
Thread is running!
Synchronization with Locks
When multiple threads access shared resources simultaneously, it can lead to race conditions and unexpected behavior. To prevent such issues, Python provides Locks. A Lock ensures that only one thread can access the shared resource at a time.
import threading
shared_resource = 0
lock = threading.Lock()
def update_shared_resource():
global shared_resource
for _ in range(100000):
lock.acquire()
shared_resource += 1
lock.release()
threads = [threading.Thread(target=update_shared_resource) for _ in range(5)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print("Shared Resource:", shared_resource)
The provided code is an example of using multithreading to update a shared resource safely using locks to avoid race conditions. Let’s break down what the code does:
shared_resource: This is a shared variable that multiple threads will try to modify concurrently.
lock: This is a threading Lock object that ensures only one thread can acquire the lock at a time, preventing other threads from accessing the shared resource simultaneously.
update_shared_resource(): This function is the target function for each thread. It contains a loop that increments the shared_resource 100,000 times. Before incrementing, it acquires the lock using lock.acquire() and releases it after updating the shared resource using lock.release(). This ensures that only one thread can modify the shared_resource at any given time.
threads: This is a list that holds five threads, each with the update_shared_resource() function as its target.
for thread in threads: thread.start(): This loop starts all the threads, allowing them to execute their target function concurrently.
The purpose of using the Lock (lock) is to ensure that each thread acquires the lock before updating the shared_resource. This prevents race conditions where multiple threads might try to update the shared_resource simultaneously, leading to unpredictable results.
With the use of locks, the code ensures that the shared_resource is updated correctly and consistently, without any race conditions. The final value of the shared_resource will be the sum of all increments performed by each thread, i.e., shared_resource = 100000 * 5 = 500000.
Thread Pooling
Creating and destroying threads can be costly. Thread pooling allows you to reuse a fixed number of threads, reducing overhead.
import concurrent.futures
def task_function(task_id):
print(f"Task {task_id} is running")
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
tasks = [executor.submit(task_function, i) for i in range(5)]
Dealing with Race Conditions
Race conditions occur when multiple threads access shared resources and try to modify them simultaneously, leading to unpredictable results. Using locks and synchronization techniques can help avoid race conditions.
Benefits and Considerations
Multithreading can improve the performance of I/O-bound tasks, but it may not be ideal for CPU-bound tasks due to the Global Interpreter Lock (GIL). Consider your application’s specific requirements and the potential challenges when deciding whether to use multithreading or other concurrency techniques.
Python multithreading is a valuable tool to achieve concurrency and improve the performance of your applications. By understanding the threading module, synchronization, communication, and pooling, you can effectively harness the power of multithreading.
