Multithreading Basics
Threading lets you run multiple tasks concurrently. Good for I/O-bound tasks (network, file operations) but limited by the GIL for CPU-bound tasks.
15 min•By Priygop Team•Updated 2026
Multithreading
Multithreading
import threading
import time
# Basic thread
def download(url, delay=1):
print(f" Downloading {url}...")
time.sleep(delay * 0.01) # Simulated delay
print(f" Done: {url}")
# Sequential
start = time.time()
download("file1.zip", 2)
download("file2.zip", 3)
print(f" Sequential: {time.time() - start:.2f}s")
# Parallel with threads
start = time.time()
t1 = threading.Thread(target=download, args=("file3.zip", 2))
t2 = threading.Thread(target=download, args=("file4.zip", 3))
t1.start()
t2.start()
t1.join()
t2.join()
print(f" Parallel: {time.time() - start:.2f}s")
# Thread pool (modern approach)
from concurrent.futures import ThreadPoolExecutor
urls = ["page1", "page2", "page3", "page4"]
with ThreadPoolExecutor(max_workers=4) as executor:
executor.map(download, urls)
print(" All downloads complete!")
# Thread safety with Lock
counter = 0
lock = threading.Lock()
def safe_increment():
global counter
for _ in range(1000):
with lock:
counter += 1
threads = [threading.Thread(target=safe_increment) for _ in range(5)]
for t in threads: t.start()
for t in threads: t.join()
print(f" Counter: {counter}") # 5000 (correct!)Tip
Tip
Use threading for I/O-bound tasks (network, file). Use multiprocessing for CPU-bound tasks. The GIL limits threading for CPU work.
Diagram
Loading diagram…
asyncio for I/O. multiprocessing for CPU.
Common Mistake
Warning
Shared mutable state with threads causes race conditions. Use threading.Lock or Queue for thread-safe communication.
Quick Quiz
Practice Task
Note
(1) Download multiple URLs concurrently with threading. (2) Use Lock to protect shared data. (3) Compare serial vs parallel execution time.