Operating systems questions are a staple of campus placements and early-career interviews in India, and "processes versus threads" is the one almost everyone gets. Concurrency then shows up again in senior rounds: in low-level design ("make this cache thread-safe"), in system design ("what if two requests update the same row?"), and in debugging rounds, where race conditions are a favourite bug to plant.
This article covers the concepts you need, with code you can run, and ends with the questions interviewers actually ask.
Processes and threads
A process is a running program with its own address space: its own memory, file handles and resources, isolated from other processes by the operating system. A thread is a path of execution inside a process. Threads in the same process share its memory and resources, but each has its own stack, registers and program counter.
| Process | Thread | |
|---|---|---|
| Memory | Own address space | Shares the process's memory |
| Creation cost | Higher (new address space, page tables) | Lower |
| Communication | Inter-process communication: pipes, sockets, shared memory | Directly through shared variables |
| Isolation | A crash usually stays inside the process | A crash in one thread can take down the whole process |
| Context switch | Slower (switch address space, flush TLB entries) | Faster (same address space) |
A useful analogy: a process is a flat, threads are the people living in it. They share the kitchen (memory), which is efficient and is also exactly why they can get in each other's way.
Real systems use both. Chrome runs each tab as a separate process so one crashing page doesn't kill the browser. A web server like Tomcat handles requests on a pool of threads inside one process, because sharing memory (caches, connection pools) is cheap.
Context switches, concurrency and parallelism
A CPU core runs one thread at a time. The operating system's scheduler gives each runnable thread a time slice, then saves its state (registers, program counter, stack pointer) and restores another's. That is a context switch. It costs microseconds. That's cheap on its own, but expensive when a system with thousands of threads spends its time switching rather than working.
Two words that interviewers want you to separate:
- Concurrency is about dealing with many things at once: tasks whose lifetimes overlap, possibly interleaved on one core.
- Parallelism is about doing many things at once: tasks literally running at the same instant on different cores.
A single-core machine can be concurrent but not parallel. Node.js is concurrent (many requests in flight, interleaved at await points) on a single JavaScript thread.
Race conditions
A race condition happens when the result depends on the timing of threads that touch shared data. The classic example is incrementing a counter. count++ looks like one step, but it is three: read the value, add one, write it back. If two threads both read 41, both write 42, and one increment is lost.
The code below runs four threads that each increment shared counters 100,000 times. The unprotected counter ends up short; the locked and atomic ones are always exactly 400,000. (CPython normally switches threads only every few milliseconds, so the Python version asks it to switch far more often. Without that line the bug is still there, just rarer and harder to reproduce, which is exactly what makes race conditions dangerous.) JavaScript has no shared-memory threads here, but the same bug appears when a read-modify-write spans an await.
import sys
import threading
sys.setswitchinterval(1e-6) # switch threads very often, so the race shows up quickly
unsafe = 0
locked = 0
lock = threading.Lock()
def add_one(x: int) -> int: # any real work between the read and the write
return x + 1
def work(n: int) -> None:
global unsafe, locked
for _ in range(n):
current = unsafe # read
unsafe = add_one(current) # write: another thread may have written in between
with lock: # read-modify-write as one step
locked = add_one(locked)
threads = [threading.Thread(target=work, args=(100_000,)) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"unsafe={unsafe} locked={locked}") # unsafe ends up below 400000; locked never doesThe fix always has the same shape: make the read-modify-write happen as one indivisible step, either by holding a lock around it or by using an atomic operation. In databases, the same idea is UPDATE accounts SET balance = balance + 100 WHERE id = 7 instead of reading the balance into your application and writing it back.
Synchronisation tools
| Tool | What it does | Use it for |
|---|---|---|
| Mutex (lock) | Only one thread holds it at a time | Protecting a critical section that reads and writes shared data |
| Read–write lock | Many readers or one writer | Read-heavy data that changes rarely (a config map) |
| Semaphore | A counter of permits; threads wait when it reaches zero | Limiting concurrency, e.g. at most 10 database connections in use |
| Condition variable | Lets a thread sleep until another signals that something changed | Waiting for a queue to become non-empty |
| Atomic variable | Hardware-level indivisible operations (increment, compare-and-swap) | Counters, flags, lock-free structures |
Mutex versus binary semaphore is a common follow-up. A mutex has an owner: only the thread that locked it should unlock it, and many implementations enforce that. A semaphore has no owner (any thread can signal it), which makes it a signalling tool as much as a locking one.
Compare-and-swap (CAS) is worth knowing by name: "set this value to new only if it is still expected", done atomically by the CPU. It is the building block for atomics and lock-free algorithms, and the same idea appears in databases as optimistic locking (UPDATE … WHERE version = 7).
Deadlock
A deadlock is when threads wait for each other forever. Thread A holds lock 1 and waits for lock 2; thread B holds lock 2 and waits for lock 1. Neither can proceed.
Deadlock needs all four Coffman conditions at once:
- Mutual exclusion: a resource can be held by only one thread.
- Hold and wait: a thread holds one resource while waiting for another.
- No preemption: resources can't be taken away; they must be released.
- Circular wait: a cycle of threads, each waiting for the next.
Break any one and deadlock is impossible. In practice:
- Lock ordering breaks circular wait: always acquire locks in the same global order (for example by account id). This is the answer interviewers want for "transfer money between two accounts without deadlock".
- Timeouts (
tryLockwith a timeout) break hold-and-wait: give up, release what you hold, and retry. - Fewer, coarser locks, or no shared state at all, avoid the problem entirely.
Related terms: livelock (threads keep reacting to each other and make no progress, like two people stepping aside in a corridor forever) and starvation (a thread never gets a turn because others always win).
Producer–consumer
One of the most common concurrency patterns: producers put work into a bounded queue, consumers take it out. The queue decouples their speeds, and the bound provides backpressure: when consumers fall behind, producers block instead of filling memory.
Every language has a ready-made version: queue.Queue in Python, BlockingQueue in Java, buffered channels in Go. Interviewers sometimes ask you to build one with a mutex and two condition variables ("not full" and "not empty"). The key detail: wait in a while loop, not an if, because a thread can wake up and find the condition false again (spurious wake-ups, or another consumer got there first).
The same pattern scales up to whole systems. A message queue between services is producer–consumer across machines. See message queues: Kafka vs RabbitMQ.
Thread pools
Creating a thread per task is expensive and unbounded. A thread pool keeps a fixed number of worker threads pulling tasks from a queue. Sizing rule of thumb: for CPU-bound work, about one thread per core; for I/O-bound work, more, because threads spend most of their time waiting. Java's ExecutorService, Python's concurrent.futures.ThreadPoolExecutor and most web servers are built this way.
Language notes interviewers like
- Python's GIL: in CPython, the Global Interpreter Lock lets only one thread run Python bytecode at a time. Threads still help for I/O-bound work (waiting on the network releases the GIL), but CPU-bound work needs
multiprocessing. Races still happen, because the GIL protects the interpreter, not your read-modify-write. - Java:
synchronized,volatile(visibility of writes across threads, not atomicity),java.util.concurrent(locks, atomics, concurrent maps, executors). - JavaScript: one thread per event loop; concurrency through
async/await. Shared-memory parallelism exists only with Worker threads andSharedArrayBuffer/Atomics. - Go: goroutines are cheap, multiplexed onto OS threads by the runtime; "share memory by communicating" through channels, with
sync.Mutexwhen you do share.
Questions interviewers ask
- What is the difference between a process and a thread? Address space, cost, communication and isolation. Use the table above.
- What happens during a context switch, and why is it costly? Saving and restoring registers and state, and for processes switching the address space; caches and TLB entries go cold.
- What is a race condition? Give an example. The counter, or two users booking the last seat.
- Mutex versus semaphore? Ownership and counting.
- What is a deadlock, and how do you prevent it? The four conditions; lock ordering.
- What does "thread-safe" mean? Correct behaviour when called from multiple threads at once, without extra synchronisation by the caller.
- Concurrency versus parallelism? Dealing with versus doing many things at once.
- How would you make an LRU cache thread-safe? A lock around both operations, then sharding for scale. See the LRU cache design.
- Why doesn't Python's GIL make my code thread-safe? It protects the interpreter's internals; your multi-step operations can still interleave.
- How do two services avoid both processing the same job? Database row locks (
SELECT … FOR UPDATE SKIP LOCKED), leases, or a queue that delivers each message to one consumer, plus idempotency, because retries happen anyway.
If you can explain the counter race, fix it two ways, and explain why lock ordering prevents deadlock, you will handle most concurrency questions in early-career interviews.