Explain concurrency patterns and pitfalls: threads, async I/O, locks, queues, actors, deadlocks, race conditions, and testing strategies. Include code examples and performance trade-offs across approaches.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Concurrency allows programs to handle multiple tasks "simultaneously," improving throughput for I/O-bound (e.g., network calls) or CPU-bound (e.g., computations) workloads. However, it introduces pitfalls like race conditions and deadlocks. Below, I explain key patterns (threads, async I/O, locks, queues, actors), pitfalls, testing strategies, with Python code examples (using threading, asyncio, queue, and a simple actor simulation via multiprocessing). I'll highlight performance trade-offs.
1. Threads
Pattern: OS threads (via threading module) run concurrently, sharing memory. Ideal for I/O-bound tasks in Python (despite GIL limiting CPU parallelism).
Example (I/O-bound: fetching URLs):
python
import threading
import requests
import time
def fetch(url):
start = time.time()
response = requests.get(url)
print(f"{url}: {time.time() - start:.2f}s")
urls = ['https://httpbin.org/delay/1'] * 5
threads = [threading.Thread(target=fetch, args=(url,)) for url in urls]
start = time.time()
for t in threads: t.start()
for t in threads: t.join()
print(f"Total: {time.time() - start:.2f}s") # ~1s vs 5s sequential
Trade-offs:
Pros: Simple shared state; good for I/O (context switches during waits).
Cons: GIL blocks CPU parallelism (use multiprocessing for CPU-bound); overhead ~1MB/thread; hard to debug.
2. Async I/O
Pattern: Cooperative multitasking on a single thread (via asyncio). Tasks yield control during I/O waits. Best for I/O-bound, high-concurrency apps (e.g., web servers).
Example (same URL fetch):
python
import asyncio
import aiohttp
import time
async def fetch(session, url):
start = time.time()
async with session.get(url) as response:
print(f"{url}: {time.time() - start:.2f}s")
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
tasks = [fetch(session, 'https://httpbin.org/delay/1') for _ in range(5)]
start = time.time()
await asyncio.gather(*tasks)
print(f"Total: {time.time() - start:.2f}s")
asyncio.run(main()) # ~1s
Trade-offs:
Pros: No locks needed (event loop); scales to 100k+ connections; low overhead (~few KB/coroutine).
Cons: Callback hell without async/await; single-threaded (bad for CPU-bound); "async code smells" like blocking calls.
import threading
counter = 0
lock = threading.Lock()
def increment():
global counter
for _ in range(100000):
with lock: # Acquire/release automatically
counter += 1
threads = [threading.Thread(target=increment) for _ in range(10)]
for t in threads: t.start()
for t in threads: t.join()
print(counter) # 1,000,000 (correct)
Alternatives: Read-write locks (RWLock), semaphores for N-way access.
4. Queues
Pattern: Producer-consumer via thread-safe queues (queue.Queue). Decouples components, bounds memory.
Example:
python
import threading
import queue
import time
q = queue.Queue(maxsize=5) # Bounded
def producer():
for i in range(5):
time.sleep(0.1)
q.put(i) # Blocks if full
print(f"Produced {i}")
def consumer():
while True:
item = q.get() # Blocks if empty
print(f"Consumed {item}")
q.task_done()
threads = [threading.Thread(target=producer), threading.Thread(target=consumer)]
for t in threads: t.start()
threads[1].join(timeout=1) # Graceful shutdown
Trade-offs:
Pros: Backpressure; hides latency spikes.
Cons: Serialization limits throughput; memory if unbounded.
Async variant: asyncio.Queue.
5. Actors
Pattern: Isolated state + message-passing (inspired by Erlang/Akka). Each actor processes one message at a time, no shared mutable state. Libraries: pykka, thespian; simulate with multiprocessing.
Example (simple actor for counter):
python
import multiprocessing as mp
import queue
class CounterActor(mp.Process):
def __init__(self):
super().__init__()
self mailbox = mp.Queue()
def run(self):
count = 0
while True:
msg = self.mailbox.get()
if msg == 'STOP': break
count += msg
print(f"Count: {count}")
def send(self, msg):
self.mailbox.put(msg)
actor = CounterActor()
actor.start()
for i in range(5): actor.send(i)
actor.send('STOP')
actor.join()
Trade-offs:
Pros: Fault-tolerant (supervision hierarchies); scales distributed; no locks.
Cons: Message overhead (serialization/network); harder to reason about ordering; higher latency (~10x threads for local).
Pitfalls
Race Conditions
Issue: Unprotected shared state leads to inconsistent results (e.g., lost updates).
Bad Example (without lock):
python
counter = 0
def increment():
global counter
for _ in range(100000): # Race: read-modify-write not atomic
counter += 1 # May interleave: read 5, both write 6 → lost increment
# Run 10 threads → counter ~800k (wrong!)
Fix: Locks or atomics (threading.atomic via concurrent.futures).
Deadlocks
Issue: Circular wait for locks (e.g., acquire A→B in one thread, B→A in another).
Bad Example:
python
lock1, lock2 = threading.Lock(), threading.Lock()
counter1, counter2 = 0, 0
def thread1():
with lock1:
time.sleep(0.1) # Simulate work
with lock2: # Deadlock if thread2 holds lock2
pass
def thread2():
with lock2:
time.sleep(0.1)
with lock1:
pass
threading.Thread(target=thread1).start()
threading.Thread(target=thread2).start()
# Hangs!
Fixes: Lock ordering (always A→B), timeouts (lock.acquire(timeout=1)), RLock for reentrancy, or lock-free (queues/actors).
Other pitfalls: Livelock (spinning), starvation (unfair locks), priority inversion.
Testing Strategies
Unit Tests: Use threading.Barrier/asyncio.Semaphore for synchronization; concurrent.futures for pools.