techmore.in

Python - Multithreading

What is Multithreading?

Multithreading is a technique where multiple threads (smaller units of a process) are run concurrently to improve performance. It helps in parallel execution of tasks like I/O operations, timers, and UI handling.

Why Use Multithreading?

  • To perform multiple tasks simultaneously
  • To improve responsiveness in applications (like GUI apps)
  • To handle I/O-bound operations efficiently

How to Use Multithreading in Python?

Python provides the threading module to implement multithreading. A thread is created by instantiating the Thread class and calling its start() method.

python
import threading

def print_numbers():
    for i in range(5):
        print(f"Number: {i}")

t1 = threading.Thread(target=print_numbers)
t1.start()
t1.join()  # Wait for thread to finish

Creating Threads by Subclassing

python
class MyThread(threading.Thread):
    def run(self):
        for i in range(3):
            print("Thread running")

t2 = MyThread()
t2.start()
t2.join()

Thread Synchronization

Use Lock to prevent race conditions where multiple threads access shared resources.

python
lock = threading.Lock()

counter = 0

def increment():
    global counter
    for _ in range(100000):
        with lock:
            counter += 1

threads = []
for i in range(2):
    t = threading.Thread(target=increment)
    t.start()
    threads.append(t)

for t in threads:
    t.join()

print(counter)

Threading vs Multiprocessing

  • Multithreading: Best for I/O-bound tasks, shares memory space
  • Multiprocessing: Best for CPU-bound tasks, uses separate memory space

When to Use Multithreading?

  • Handling multiple I/O operations (e.g. file reading, downloading)
  • Running background tasks in GUI applications
  • Real-time monitoring and logging tasks

Pros and Cons

  • Pros: Efficient for I/O-bound programs, faster responsiveness
  • Cons: Python GIL limits true parallelism, harder to debug

Conclusion

Multithreading in Python allows you to build responsive and efficient programs, especially useful for I/O-bound tasks. Use locks and synchronization mechanisms wisely to avoid issues like race conditions.