Concurrency Models: Processes, Threads, and Shared Memory Safety
BehavioralModel answerLast updated
Contrast processes and threads in terms of isolation and resource sharing, then explain synchronization challenges in multithreaded programs.
Concurrency Models: Processes, Threads, and Shared Memory Safety
Operating systems provide different abstractions for concurrent execution. Understanding these models and their trade-offs is essential for building correct, efficient software.
Part 1: Architectural Differences
Compare and contrast processes versus threads along these dimensions:
- How memory address spaces are organized and isolated
- Ownership of system resources like file handles and network connections
- The computational cost of creating new execution units and switching between them
Part 2: Shared Memory Challenges
When multiple threads execute within the same process, they can directly read and write the same memory locations. Identify two distinct categories of bugs that emerge from this shared-memory model, explaining the underlying mechanism that causes each problem.
Part 3: Correctness Strategies
Describe practical approaches developers use to prevent these concurrency bugs. Include specific synchronization mechanisms and explain when each is appropriate.
Concrete Scenario
Consider a shared variable total = 0 accessed by two threads that each execute total = total + 1 one time. Walk through why the final value might be 1 instead of the expected 2, and explain what guarantees are needed to ensure correctness.
Hints
Hint 1
Think about what happens at the assembly or bytecode level when incrementing a variable—it's not a single instruction
Hint 2
Memory operations can be reordered by compilers and CPUs, and cores cache values independently
Hint 3
Different synchronization tools have different performance characteristics and semantic guarantees
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Concurrency Models and Memory Safety
Processes vs. Threads: Core Distinctions
Processes represent the operating system's unit of isolation and resource allocation. Threads represent the unit of execution and scheduling. A process contains at least one thread; multiple threads within a process share most resources while maintaining separate execution contexts.
| Dimension | Process | Thread |
|---|---|---|
| Virtual memory | Isolated address space with separate page tables | Shared address space with other threads in the process |
| Heap and global data | Private copy (often via copy-on-write after fork) | Fully shared across all threads |
| Stack | Private | Each thread maintains its own stack |
| CPU state (registers, PC) | Per-thread | Per-thread |
| File descriptors and handles | Process-owned, inherited by all threads | Shared—closing a descriptor affects all threads |
| Crash isolation | Failure contained within process boundaries | Any thread's memory error crashes the entire process |
| Creation overhead | Substantial: allocate page tables, kernel structures, initial memory | Lightweight: allocate stack and minimal kernel state |
| Context switching cost | Expensive: change address space mappings, flush TLB unless hardware-tagged, reload caches | Cheap: save/restore registers only, address space unchanged, caches stay warm |
Bottom line: Processes provide strong isolation with higher overhead and require explicit inter-process communication (pipes, sockets, shared memory segments). Threads provide efficient communication through shared memory but sacrifice isolation and safety.
Why total = total + 1 Can Produce 1
The increment operation decomposes into multiple steps at the machine level:
LOAD r1, [total] ; read current value into register
ADD r1, r1, 1 ; increment register
STORE [total], r1 ; write result back to memory
These steps are not atomic—the operating system can preempt and switch threads between any two instructions. Here's a failure scenario:
| Time | Thread 1 | Thread 2 | Value of total |
|---|---|---|---|
| t0 | reads 0 into r1 | — | 0 |
| t1 | — | reads 0 into r2 | 0 |
| t2 | computes 1 in r1 | computes 1 in r2 | 0 |
| t3 | writes 1 to total | — | 1 |
| t4 | — | writes 1 to total | 1 |
Thread 2's write overwrites Thread 1's result—this is called a lost update. To guarantee the final value is 2, the read-modify-write sequence must be atomic with respect to other threads: no interleaving of operations on the same variable is allowed.
Two approaches achieve this:
- Mutual exclusion: Use a mutex to ensure only one thread executes the critical section at a time
- Atomic instructions: Use hardware primitives like compare-and-swap or fetch-and-add that complete indivisibly
Two Categories of Concurrency Hazards
1. Race Conditions in Compound Operations
When an operation requires multiple steps (read-then-write, check-then-act), other threads can observe or modify state between steps, causing logical errors. Beyond lost updates, examples include:
- Check-then-act bugs: Thread A checks
if balance >= amount, context switches, Thread B withdraws funds, Thread A resumes and withdraws, causing overdraft - Partial data structure updates: Thread A is halfway through rebalancing a tree when Thread B traverses it, encountering inconsistent pointers
- Lazy initialization races: Two threads both check that a singleton is null and both initialize it
2. Memory Visibility and Reordering Issues
Modern hardware and compilers reorder operations for performance. Cores cache values in registers and buffers. Without explicit synchronization:
- A write by one thread may not become visible to other threads promptly
- Operations can appear to execute in a different order than written in source code
- Compiler may optimize away repeated reads, caching a value in a register permanently
Example: Thread A writes data = 42; ready = true;. Thread B reads if ready: use(data). Without synchronization, Thread B might see ready == true but still read stale data, or spin forever because the compiler hoisted ready into a register.
Torn reads/writes are another visibility issue: reading a 64-bit value on 32-bit hardware might see half the old value and half the new. In languages like C/C++, unsynchronized conflicting access is undefined behavior.
Mitigation Strategies and Synchronization Primitives
Mutex (Mutual Exclusion Lock) Provides exclusive access to a critical section. Automatically includes memory ordering guarantees (acquire/release semantics) that solve visibility problems. Use for protecting shared data structures. Keep critical sections short to minimize contention.
Read-Write Lock Allows multiple concurrent readers or one exclusive writer. Appropriate when reads vastly outnumber writes and read operations are substantial enough to offset the lock's higher overhead.
Condition Variables Enable threads to wait efficiently for a condition to become true, always used in conjunction with a mutex. Essential for producer-consumer patterns. Always check the condition in a loop, as spurious wakeups can occur.
Atomic Operations
Hardware instructions that complete indivisibly: fetch_add, compare_and_swap, exchange. Provide fine-grained control over memory ordering (acquire, release, seq_cst). Best for counters, flags, and lock-free data structures. Lower overhead than mutexes for simple operations.
Semaphores Counting semaphores limit concurrent access to N resources (connection pools, buffer slots). Binary semaphores (count=1) function like mutexes.
Architectural Approaches Often superior to fine-grained locking:
- Eliminate sharing: Use thread-local storage with periodic aggregation, or message-passing between threads via queues
- Immutable data: If data cannot change, it's inherently thread-safe
- Lock ordering discipline: Acquire locks in a consistent global order to prevent deadlock
- Cache-line padding: Separate frequently-modified independent variables to prevent false sharing
Performance Considerations
- Thread context switch: 1–5 microseconds typically
- Process context switch: Adds TLB flush and cache cold-start overhead
- Uncontended mutex: 20–100 nanoseconds via fast-path (futex-style)
- Contended mutex: Requires kernel involvement, adds microseconds
- Atomic operation: 5–20 nanoseconds uncontended, degrades under cache-line contention
- Thread stack memory: Typically 8 MB virtual per thread (committed lazily)
Common Misconceptions
- Global Interpreter Lock (GIL) protection: Python's GIL prevents parallel bytecode execution but does not make compound operations atomic—thread switches can occur between bytecodes
- Single-core safety: Preemptive scheduling still causes races on uniprocessor systems
volatilekeyword: In C/C++,volatileprevents compiler optimizations but provides no atomicity or inter-thread ordering guarantees- Fork in multithreaded programs: Only the calling thread continues in the child process, while locks held by other threads remain locked indefinitely
Implementation Example
import threading
counter = 0
lock = threading.Lock()
# Unsafe: race condition
def increment_unsafe():
global counter
for _ in range(100000):
counter += 1 # Not atomic: load, add, store
# Safe: mutual exclusion
def increment_safe():
global counter
for _ in range(100000):
with lock:
counter += 1 # Atomic with respect to other lock holders
# Run two threads concurrently
t1 = threading.Thread(target=increment_unsafe)
t2 = threading.Thread(target=increment_unsafe)
t1.start(); t2.start()
t1.join(); t2.join()
print(f"Unsafe result: {counter}") # Often < 200000
counter = 0
t1 = threading.Thread(target=increment_safe)
t2 = threading.Thread(target=increment_safe)
t1.start(); t2.start()
t1.join(); t2.join()
print(f"Safe result: {counter}") # Always 200000
The unsafe version typically produces a value less than 200,000 due to lost updates from race conditions. The locked version always produces exactly 200,000 because the lock ensures atomic execution of the critical section and provides memory visibility guarantees.