Advanced Python Tutorial 7: Multithreading & Multiprocessing
๐ง What’s the Difference?
Multithreading uses multiple threads in the same process — great for I/O-bound tasks. But it's limited by the GIL (Global Interpreter Lock).
Multiprocessing uses separate processes — ideal for CPU-bound tasks since it bypasses the GIL.
๐ Use Cases
- Multithreading: Downloading files, web scraping, network I/O.
- Multiprocessing: Image processing, large numerical computations, simulations.
⚙️ Example: Multithreading
We’ll run two threads that simulate I/O by sleeping for a second.
import threading
import time
def download(name):
print(f"{name} starting")
time.sleep(1)
print(f"{name} done")
t1 = threading.Thread(target=download, args=("Thread 1",))
t2 = threading.Thread(target=download, args=("Thread 2",))
t1.start()
t2.start()
t1.join()
t2.join()
print("Both threads done")
⚡ Example: Multiprocessing
This time, we’ll use the multiprocessing
module to run processes in parallel.
import multiprocessing
import time
def compute(name):
print(f"{name} starting")
time.sleep(1)
print(f"{name} done")
if __name__ == "__main__":
p1 = multiprocessing.Process(target=compute, args=("Process 1",))
p2 = multiprocessing.Process(target=compute, args=("Process 2",))
p1.start()
p2.start()
p1.join()
p2.join()
print("Both processes done")
๐ Key Takeaways
- ๐งต Use threads for tasks that wait (network, disk, APIs).
- ๐ง Use processes for heavy CPU computation.
- ๐ซ GIL limits true parallelism in threads but not in processes.
Comments
Post a Comment