DEV Community

Aishwarya Raj
Aishwarya Raj

Posted on

1 1 1

Python Multithreading and Multiprocessing

1. Multithreading: Lightweight Concurrency

Threads run concurrently within the same process, sharing memory space. Python's Global Interpreter Lock (GIL) limits threads to one execution at a time, making it ideal for I/O-bound tasks but not for CPU-intensive ones.

Example: A Simple Threaded Program

import threading

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

# Create and start threads
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_numbers)

thread1.start()
thread2.start()
thread1.join()
thread2.join()
Enter fullscreen mode Exit fullscreen mode

2. Multiprocessing: True Parallelism

Multiprocessing creates separate processes with individual memory space, bypassing the GIL. It’s best for CPU-bound tasks, like data processing or simulations.

Example: Multiprocessing Basics

from multiprocessing import Process

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

if __name__ == "__main__":
    process1 = Process(target=print_numbers)
    process2 = Process(target=print_numbers)

    process1.start()
    process2.start()
    process1.join()
    process2.join()
Enter fullscreen mode Exit fullscreen mode

When to Use Which

  • Use multithreading for tasks like file I/O, database operations, or network requests.
  • Use multiprocessing for tasks like image processing, machine learning, or data analysis.

Final Thoughts: Threads vs. Processes

With threads, Python multitasks within a single process. With processes, Python achieves true parallelism across multiple cores. Together, they make your code efficient and scalable.
_ 🥂 Cheers to mastering concurrency in Python!_

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay