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()
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()
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!_
Top comments (0)