3.5.Implementation Details
Multithreading Synchronization Mechanisms
1. Lock
import threading
lock = threading.Lock()
# Use when modifying shared variables in multithreading
with lock:
shared_variable = new_value # Safe operation
2. Queue
from queue import Queue
q = Queue(maxsize=1) # Thread-safe queue
# Producer thread
q.put(data)
# Consumer thread
data = q.get(timeout=1) # 1 second timeout
3. Event
import threading
event = threading.Event()
# Thread 1: Wait for event
event.wait() # Block until event is set
# Thread 2: Set event
event.set()
# Clear event
event.clear()
Exception Handling Pattern
try:
# Code that might fail
result = network_call()
except Timeout:
# Network timeout
logging.error("Request timeout")
except ConnectionError:
# Connection error
logging.error("Connection failed")
except Exception as e:
# All other exceptions
logging.error(f"Unknown error: {e}")
traceback.print_exc() # Print stack trace
finally:
# Executed regardless of exception
cleanup_resources()
Streaming Processing Pattern
# Generator: produce data one by one, not load all at once
def stream_data():
for chunk in data_chunks:
yield chunk
# Use generator
for chunk in stream_data():
process(chunk) # Process immediately, no need to wait for all data