We are going to explain concurrency patterns and pitfalls, including:
- Threads
- Async I/O
- Locks
- Queues
- Actors
- Deadlocks
- Race Conditions
- Testing Strategies
We'll also discuss performance trade-offs and include code examples.
Let's break it down.
-
Threads:
- Threads are the smallest unit of execution that can be scheduled by an operating system.
- Example: Creating threads in Python using
threading module.
-
Async I/O:
- Asynchronous I/O allows for non-blocking operations, often using an event loop.
- Example: Using
asyncio in Python.
-
Locks:
- Locks (mutexes) are synchronization primitives used to protect shared resources.
- Example: Using
threading.Lock in Python.
-
Queues:
- Queues are used for thread-safe communication between threads or processes.
- Example:
queue.Queue in Python.
-
Actors:
- The actor model is a concurrency model where actors are independent entities that communicate via message passing.
- Example: Using
pykka in Python or implementing a simple actor with a queue and a thread.
-
Deadlocks:
- Deadlock occurs when two or more threads are blocked forever, each waiting for the other to release a resource.
-
Race Conditions:
- Race condition occurs when the behavior of the program depends on the relative timing of events.
-
Testing Strategies:
- Testing concurrent code is challenging. Strategies include unit testing with mocks, stress testing, and using tools like
pytest with plugins.
Performance Trade-offs:
- Threads: Good for I/O-bound tasks, but in Python, due to GIL, they don't run CPU-bound tasks in parallel (unless using multiprocessing).
- Async I/O: Efficient for I/O-bound tasks with many connections, but requires async-compatible libraries and can be complex.
- Locks: Can cause contention and reduce performance if overused.
- Queues: Help in decoupling, but add overhead of message passing.
- Actors: Can simplify design but might have overhead of message passing and scheduling.
Let's write code examples for each pattern and then discuss pitfalls and testing.
Note: We are using Python for examples, but concepts are general.
We'll create:
a) Thread example: two threads incrementing a shared counter with and without lock.
b) Async I/O example: using asyncio to fetch multiple URLs.
c) Lock example: using a lock to protect a shared resource.
d) Queue example: producer-consumer with threads and a queue.
e) Actor example: a simple actor that processes messages from a queue.
Then, we'll show a deadlock and a race condition.
For testing, we'll show an example of testing a concurrent function with pytest and pytest-asyncio for async.
Let's code accordingly.
Concurrency Patterns & Pitfalls: A Comprehensive Guide
1. Threads
Pattern: OS-managed execution units sharing memory space.
# Python threading example
import threading
import time
def worker(name):
print(f"{name} starting")
time.sleep(1)
print(f"{name} finished")
threads = []
for i in range(3):
t = threading.Thread(target=worker, args=(f"Thread-{i}",))
threads.append(t)
t.start()
for t in threads:
t.join()
Trade-offs:
- ✅ Good for I/O-bound tasks
- ✅ Simple mental model
- ❌ GIL limits CPU parallelism (Python)
- ❌ Memory overhead (~8MB/thread stack)
- ❌ Context switching cost (~1-10μs)
2. Async I/O (Event-Driven)
Pattern: Single-threaded cooperative multitasking with event loop.
# Python asyncio example
import asyncio
async def fetch_data(url):
print(f"Fetching {url}")
await asyncio.sleep(0.5) # Simulate I/O
return f"Data from {url}"
async def main():
urls = ["url1", "url2", "url3"]
tasks = [fetch_data(url) for url in urls]
results = await asyncio.gather(*tasks)
print(results)
asyncio.run(main())
Trade-offs:
- ✅ High throughput for I/O-bound (1000s of connections)
- ✅ Low memory footprint (no thread stacks)
- ❌ CPU-bound tasks block entire loop
- ❌ Requires async-compatible libraries
- ❌ Debugging complexity (stack traces)
3. Locks (Mutexes)
Pattern: Mutual exclusion for shared resources.
import threading
class Counter:
def __init__(self):
self._value = 0
self._lock = threading.Lock()
def increment(self):
with self._lock: # Automatic acquire/release
self._value += 1
@property
def value(self):
with self._lock:
return self._value
Trade-offs:
- ✅ Simple safety guarantee
- ✅ Widely supported
- ❌ Contention: Threads block waiting
- ❌ Priority inversion risk
- ❌ Deadlock if not careful
4. Queues (Producer-Consumer)
Pattern: Thread-safe communication channel.
from queue import Queue
import threading
import time
def producer(q, items):
for i in range(items):
time.sleep(0.1)
q.put(i)
q.put(None) # Sentinel
def consumer(q):
while True:
item = q.get()
if item is None:
break
print(f"Processing {item}")
q.task_done()
q = Queue(maxsize=3) # Bounded buffer
threads = [
threading.Thread(target=producer, args=(q, 5)),
threading.Thread(target=consumer, args=(q,))
]
for t in threads:
t.start()
q.join() # Wait for all tasks
Trade-offs:
- ✅ Decouples producers/consumers
- ✅ Natural backpressure (bounded queues)
- ✅ Thread-safe by design
- ❌ Memory overhead for buffering
- ❌ Context switching between threads
5. Actors
Pattern: Entities with private state + message-passing.
# Simplified actor implementation
import threading
from queue import Queue
class Actor:
def __init__(self):
self._mailbox = Queue()
self._running = True
self._thread = threading.Thread(target=self._run)
self._thread.start()
def _run(self):
while self._running or not self._mailbox.empty():
try:
msg = self._mailbox.get(timeout=0.1)
self._receive(msg)
self._mailbox.task_done()
except:
continue
def send(self, msg):
self._mailbox.put(msg)
def _receive(self, msg):
raise NotImplementedError
def stop(self):
self._running = False
self._thread.join()
# Usage
class CounterActor(Actor):
def __init__(self):
super().__init__()
self._count = 0
def _receive(self, msg):
if msg == "inc":
self._count += 1
elif msg == "get":
print(f"Count: {self._count}")
actor = CounterActor()
actor.send("inc")
actor.send("inc")
actor.send("get")
actor.stop()
Trade-offs:
- ✅ No shared state → no locks needed
- ✅ Natural error isolation
- ✅ Location transparency
- ❌ Message serialization overhead
- ❌ Complex debugging (message flows)
- ❌ Potential for mailbox buildup
Common Pitfalls
6. Deadlock
Scenario: Thread A holds Lock1, needs Lock2; Thread B holds Lock2, needs Lock1.
import threading
import time
lock_a = threading.Lock()
lock_b = threading.Lock()
def thread1():
with lock_a:
time.sleep(0.1) # Timing window
with lock_b: # Blocked if thread2 holds lock_b
print("Thread1")
def thread2():
with lock_b:
time.sleep(0.1)
with lock_a: # Blocked if thread1 holds lock_a
print("Thread2")
t1 = threading.Thread(target=thread1)
t2 = threading.Thread(target=thread2)
t1.start(); t2.start()
t1.join(); t2.join() # DEADLOCK!
Solutions:
- Lock ordering: Always acquire locks in same global order
- Timeouts:
lock.acquire(timeout=1)
- Deadlock detection: Graph-based algorithms (rare in practice)
- Avoid locks: Use queues/actors instead
7. Race Condition
Scenario: Non-atomic operation between threads.
# BROKEN - race condition!
class UnsafeCounter:
def __init__(self):
self.value = 0
def increment(self):
self.value += 1 # NOT atomic: read-modify-write
# Fix with lock (see above) or atomic operations
from threading import Lock
class SafeCounter:
def __init__(self):
self._value = 0
self._lock = Lock()
def increment(self):
with self._lock:
self._value += 1
Other race examples:
- Check-then-act:
if not cache[key]: cache[key] = compute()
- Publication: Constructor escapes
this reference before object fully constructed
- Iteration: Modifying collection during iteration
Performance Comparison
| Approach | Latency | Throughput | Memory | Best For | Worst For |
|---|
| Threads | Medium | Medium | High | Mixed I/O+CPU | Many connections |
| Async I/O | Low* | Very High | Low | High-connection I/O | CPU-bound |
| Locks | Variable | Low (content.) | Low | Fine-grained shared state | High contention |
| Queues | Medium | Medium | Medium | Pipeline processing | Low-latency needs |
| Actors | High | Medium | Medium | Isolated components | Shared data |
| Processes | High | High (CPU) | Very High | CPU-bound, multi-core | Shared state |
*Async latency low for I/O, high for sequential CPU tasks
Key insights:
- Thread creation: ~1-10ms, context switch: ~1-10μs
- Async yield: ~0.1-1μs (much cheaper than thread switch)
- Lock contention: Spinning wastes CPU, blocking adds scheduling cost
- Actor messaging: ~0.1-10μs (in-process), ~1-100μs (inter-process)
Testing Strategies
1. Deterministic Testing
# Force ordering for reproducibility
import unittest
from unittest.mock import MagicMock
class TestConcurrent(unittest.TestCase):
def test_race_condition(self):
# Use barriers to control timing
from threading import Barrier
barrier = Barrier(2)
counter = SafeCounter()
def increment():
barrier.wait() # Both threads start simultaneously
for _ in range(1000):
counter.increment()
threads = [threading.Thread(target=increment) for _ in range(2)]
for t in threads: t.start()
for t in threads: t.join()
self.assertEqual(counter.value, 2000)
2. Stress Testing
# Run many iterations to expose rare races
def stress_test(func, iterations=10000, threads=10):
errors = []
def worker():
try:
for _ in range(iterations):
func()
except Exception as e:
errors.append(e)
threads = [threading.Thread(target=worker) for _ in range(threads)]
for t in threads: t.start()
for t in threads: t.join()
return errors
3. Static Analysis
- ThreadSanitizer (TSan): C/C++/Go/Rust
- Helgrind: Valgrind tool for pthreads
- Python:
pytest + pytest-xdist + custom decorators
4. Property-Based Testing
# Using Hypothesis for race discovery
from hypothesis import given, strategies as st
import threading
@given(st.integers(), st.integers())
def test_commutative_operations(a, b):
# Run operations in random order
results = []
def op1():
results.append(("op1", a+b))
def op2():
results.append(("op2", a*b))
# Random scheduling
t1 = threading.Thread(target=op1)
t2 = threading.Thread(target=op2)
t1.start(); t2.start()
t1.join(); t2.join()
# Verify invariants
assert len(results) == 2
5. Model Checking
- TLA+: Formal specification → exhaustive state exploration
- Java Pathfinder: JVM bytecode model checker
- Python:
all paths with bounded schedules (research tools)
Pattern Selection Guide
| Scenario | Recommended Approach | Why |
|---|
| 1000s of HTTP connections | Async I/O | Minimal overhead per connection |
| CPU-intensive parallel computation | Multiprocessing/ThreadPool | Bypass GIL, utilize multiple cores |
| Real-time game physics | Actor model + thread pool | Isolated entities, predictable timing |
| Shared cache with many readers | Reader-writer lock | Allows concurrent reads |
| Data pipeline (ETL) | Queue-based workers | Natural backpressure, fault isolation |
| Microservices communication | Message queue (RabbitMQ/Kafka) | Network transparency, durability |
Advanced Considerations
Hybrid Approaches
# Thread pool + async I/O (best of both worlds)
import asyncio
from concurrent.futures import ThreadPoolExecutor
async def process_image(url):
# I/O in async, CPU in thread pool
data = await fetch_async(url)
loop = asyncio.get_running_loop()
result = await loop.run_in_executor(
None, # Default thread pool
cpu_intensive_filter, # Blocking CPU work
data
)
return result
Common Anti-Patterns
- Lock granularity too fine: Contention overhead > critical section
- Async in CPU loop: Starves event loop
- Blocking calls in async:
time.sleep() vs asyncio.sleep()
- Shared mutable state: Prefer immutable data or copy-on-write
- Unbounded queues: Memory leak risk
Performance Tuning Checklist
Key Takeaways
- Start simple: Single-threaded async if I/O-bound, process pool if CPU-bound
- Prefer message passing (queues/actors) over shared state
- Measure everything: Concurrency bugs are timing-dependent
- Design for failure: Assume any operation can block indefinitely
- Know your runtime: GIL (Python), JVM memory model, Go scheduler
- Use existing frameworks: Don't reinvent actors (Akka, Orleans, Pykka)
- Test with production-like loads: Race conditions appear at scale
Golden rule: If you can avoid explicit concurrency (batch processing, request-per-process), do so. Concurrency complexity grows exponentially with each additional interacting component.