- Phase: 10. Concurrency & Internals
- Duration: 2.5 hours
- Understand concurrency vs parallelism
- Create and manage threads with the threading module
- Use daemon threads for background tasks
- Ensure thread safety with Lock and RLock
- Explain the GIL and its implications
- Avoid race conditions with proper synchronization
- Use queue for thread-safe communication
- Concurrency vs parallelism
- threading module: Thread, start, join
- Daemon threads
- Thread safety: Lock, RLock
- GIL (Global Interpreter Lock)
- Race conditions
- queue module for thread-safe communication
- Producer-consumer pattern
Modules 000-090.
import threading
from typing import List, Thread
# Create and start threads
def worker(name: str) -> None:
print(f"Thread {name} running")
threads: List[Thread] = []
for i in range(5):
t = threading.Thread(target=worker, args=(f"T-{i}",))
t.start()
threads.append(t)
for t in threads:
t.join() # Wait for completion
# Thread safety with Lock
lock: threading.Lock = threading.Lock()
shared_counter: int = 0
def safe_increment() -> None:
global shared_counter
with lock:
shared_counter += 1
# Thread-safe queue
from queue import Queue
q: Queue = Queue()
q.put("item")
item = q.get()- Python threading documentation
- Python queue documentation
- "Python Concurrency" chapter in Fluent Python
- GIL explained: https://realpython.com/python-gil
Module 092: Concurrency: Multiprocessing