Skip to content
Visual explainer 5h to learn 5 steps

Operating systems: processes, threads, memory, deadlocks

Answer OS questions with concrete examples.

By Invicly Tech, , in Interview Preparation. About 13 minutes to read.

Topic 19 of 27

In short

The operating system shares the CPU and memory among programs. Interviews ask about processes versus threads, scheduling, virtual memory and how deadlocks happen and are prevented.

Explained simply

An operating system (OS) is the program that runs all other programs. Your laptop may have hundreds of programs open, but only a few CPU cores. The OS gives each program a short turn on a core, many times per second, so they all seem to run at once.

A process is one running program with its own private memory. A thread is a worker inside a process. All threads of one process share the same memory, so they can work together quickly, but they can also step on each other's data if nobody controls access.

Memory works in a clever way. Each process thinks it owns a huge, clean block of memory starting at address zero. In reality, the OS and the hardware translate those fake addresses into real RAM, one small page at a time. This is called virtual memory.

A deadlock is when two or more threads wait for each other forever. Thread A holds lock 1 and wants lock 2; thread B holds lock 2 and wants lock 1. Neither will let go. In interviews, you should explain why it happens and one concrete way to stop it.

Press Play on a diagram to walk through it one step at a time.

CompareProcess vs thread
Process
  • Own address space
  • Isolated: a crash stays contained
  • Heavier to create and switch
  • Talk via pipes, sockets
Thread
  • Shares memory with its process
  • Cheap to create and switch
  • Needs locks for shared data
  • One crash can kill all threads
MapDeadlock needs all four conditions
Deadlock
  • Mutual exclusion
    • Resource held by one at a time
  • Hold and wait
    • Fix: request all locks up front
  • No preemption
    • Fix: tryLock with timeout, back off
  • Circular wait
    • Fix: always lock in a global order
LayersWhat a process looks like in memory
  1. 1
    Kernel space

    Mapped but not accessible from user code

  2. 2
    Stack

    One per thread, grows down, local variables

  3. 3
    Memory-mapped area

    Shared libraries, mmap'd files

  4. 4
    Heap

    malloc or new, grows up, shared by threads

  5. 5
    Data and BSS

    Global and static variables

  6. 6
    Text

    Program code, read-only

In depth

Process states and what a context switch costs

A process or thread moves between a few states. It is ready when it could run but is waiting for a CPU, running while on a core, and blocked (also called waiting) while it waits for disk, network or a lock. When the timer interrupt fires or the task blocks, the kernel saves its registers and picks another ready task. That is a context switch.

Switching between threads of the same process is cheaper because the page tables stay the same. Switching between processes means loading a new address space, and the TLB (the cache of address translations) may need flushing, so the next memory accesses are slower. A switch costs roughly a few microseconds, but the cache misses after it often cost more than the switch itself.

  • Ready: can run, waiting for a core
  • Running: on a CPU right now
  • Blocked: waiting for I/O or a lock
  • vmstat 1 shows context switches per second in the cs column
CycleLife of a thread on the CPU
  1. 1
    Ready

    Waiting in the run queue

  2. 2
    Running

    Scheduler gives it a core

  3. 3
    Blocked

    Waits for disk, network or a lock

  4. 4
    Woken up

    I/O done or lock free, back to ready

  5. Back to step 1

CPU scheduling algorithms you should name

First come, first served (FCFS) runs tasks in arrival order; one long task makes everyone wait (the convoy effect). Shortest job first (SJF) gives the lowest average waiting time but needs to know job lengths, and long jobs can starve. Round robin gives each task a fixed time slice (quantum) in turn; a small quantum feels responsive but wastes time on switches. Priority scheduling runs high priority first and uses aging (slowly raising the priority of waiting tasks) to prevent starvation.

Real systems mix these ideas. Linux used the Completely Fair Scheduler (CFS) for years, which picks the task that has had the least CPU time. Since kernel 6.6 the default is EEVDF, which also tracks fairness but adds deadlines for better latency. You do not need the formulas; know the trade-off between throughput, fairness and response time.

  • FCFS: simple, convoy effect
  • SJF: best average wait, starvation risk
  • Round robin: fair and responsive, switch overhead
  • Priority plus aging: avoids starvation

Virtual memory, paging and page faults

Memory is split into pages, usually 4 KB on x86-64. Each process has a page table that maps its virtual pages to physical frames in RAM. The MMU (memory management unit) does this lookup in hardware for every access, and the TLB caches recent lookups so most accesses are fast.

If a page is not in RAM, the CPU raises a page fault and the kernel handles it. A minor fault just maps a page that is already in memory (for example a shared library). A major fault must read the page from disk or swap, which is thousands of times slower. When the working set (pages a program actively uses) is larger than RAM, the system spends its time moving pages in and out. That is thrashing.

Virtual memory is the mapping idea; swap is just the disk area used to hold pages that do not fit in RAM.

FlowOne memory access, step by step
  1. 1
    Virtual address

    Program reads address 0x7ff...

  2. 2
    TLB lookup

    Hit: physical address in about one cycle

  3. 3
    Page table walk

    Miss: MMU reads the page table

  4. 4
    Page fault?

    Page not present: kernel takes over

  5. 5
    Load and retry

    Map or read the page, rerun the instruction

Mutexes, semaphores and condition variables

A mutex is a lock with one owner: lock it, touch the shared data, unlock it. Only the thread that locked it should unlock it. A counting semaphore holds a number N; acquire takes one unit and blocks when none are left, release gives one back. Use it to limit things, such as at most 10 database connections. A binary semaphore (N = 1) looks like a mutex but has no owner, so any thread may release it, which makes it useful for signalling.

A condition variable lets a thread sleep until some condition becomes true, for example a queue is no longer empty. The classic producer-consumer answer uses a mutex plus two condition variables (not full, not empty), or two semaphores plus a mutex. Always re-check the condition in a while loop after waking, because wakeups can be spurious.

  • Mutex: one owner, protects a critical section
  • Semaphore: counter, limits concurrency to N
  • Condition variable: wait until a condition holds
  • Spinlock: busy-waits, only for very short critical sections

Deadlock: prevention, avoidance and detection

There are three ways to deal with deadlock. Prevention breaks one of the four conditions by design: take locks in one global order, or acquire all locks at once. Avoidance checks each request before granting it; the Banker's algorithm only grants a request if the system stays in a safe state, but it needs to know maximum needs up front, so it is rare in practice. Detection lets deadlocks happen, finds cycles in a wait-for graph, then kills or rolls back a victim. Databases do exactly this: PostgreSQL checks for deadlocks after deadlock_timeout (1 second by default) and aborts one transaction.

Also know livelock (threads keep reacting to each other and make no progress, like two people stepping aside in a corridor) and starvation (one thread never gets the resource).

Learn it in 5 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Compare processes and threads~1h
  2. 2
    Learn CPU scheduling algorithms~1h
  3. 3
    Explain virtual memory and paging~1h
  4. 4
    Explain deadlock conditions and prevention~1h
  5. 5
    Prepare examples for mutexes and semaphores~1h

Key points

  • Context switches between threads are cheaper because memory mappings stay the same.
  • Virtual memory gives each process its own address space, mapped to RAM in pages.
  • A page fault loads a missing page from disk; too many cause thrashing.
  • A mutex allows one holder; a counting semaphore allows up to N.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
import threading
account_lock = threading.Lock()
audit_lock = threading.Lock()

# Every thread takes locks in the SAME order: account, then audit.
# This breaks the circular-wait condition, so no deadlock.
def transfer():
    with account_lock:
        with audit_lock:
            pass  # update balance and audit log

def report():
    with account_lock:
        with audit_lock:
            pass  # read both consistently

Answering: processes or threads for a web server?

Step 1: name the trade-off. Threads share memory, so they are cheap and can share a cache, but one bad pointer or unhandled crash can take down all of them. Processes are isolated but cost more memory and need IPC (inter-process communication) to share data. Step 2: give real examples. Nginx and PostgreSQL use multiple processes, so a crash in one worker does not kill the server. Java servers like Tomcat use a thread pool inside one JVM. Step 3: mention the language. In CPython, the GIL (global interpreter lock) lets only one thread run Python code at a time, so CPU-heavy work uses multiprocessing, while I/O-heavy work is fine with threads or asyncio.

Producer-consumer with a bounded buffer

An interviewer asks you to explain producer-consumer. A producer adds jobs to a queue of size 3; a consumer takes them out. Step 1: the producer must wait when the queue is full, and the consumer must wait when it is empty. Step 2: one semaphore counts free slots, one counts filled slots, and a lock protects the list itself. Step 3: each side waits on one semaphore and signals the other. Python's queue.Queue already does this for you, but showing the parts proves you understand it.

python
import threading
buf, lock = [], threading.Lock()
free = threading.Semaphore(3)   # empty slots
full = threading.Semaphore(0)   # filled slots
def produce(item):
    free.acquire()              # wait for a free slot
    with lock:
        buf.append(item)
    full.release()              # one more item ready
def consume():
    full.acquire()              # wait for an item
    with lock:
        item = buf.pop(0)
    free.release()
    return item

Quick reference

  • Process = own address space; thread = shares its process's memory, has its own stack and registers
  • Thread switches are cheaper: no page table change, fewer TLB and cache misses
  • Round robin: fair, responsive; small quantum means more context-switch overhead
  • Page size is usually 4 KB; the TLB caches virtual-to-physical translations
  • Major page fault reads from disk; thrashing = working set bigger than RAM
  • Mutex has one owner; counting semaphore allows N holders
  • Prevent deadlock with a global lock order or tryLock with timeout and back off
  • Deadlock = nobody moves; livelock = everyone moves, nobody progresses; starvation = one never runs

Common mistakes

  • Saying threads are always faster; CPU-bound Python threads are limited by the GIL.
  • Listing deadlock conditions without a concrete prevention example.
  • Confusing virtual memory with swap space.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which scheduling algorithm gives the lowest average waiting time if job lengths are known?

Question 2

2What is thrashing?

Question 3

3Which statement about a counting semaphore initialised to 5 is correct?

Question 4

4Two threads each lock A then B. A third thread locks B then A. Which deadlock condition can you remove by fixing the third thread?

Question 5

5Why is switching between two threads of the same process usually cheaper than between two processes?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Explain, in three sentences, the difference between a process and a thread, with one real program as an example of each.

  2. Exercise 2medium

    Three tasks arrive at time 0 with burst times 6, 2 and 4 ms (in that order). Compute the average waiting time for FCFS and for SJF.

  3. Exercise 3hard

    Write a Python function transfer(a, b, amount) for Account objects that each have their own lock, so that two opposite transfers running at once can never deadlock.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is virtual memory the same as swap?
No. Virtual memory is the address translation that gives each process its own address space. Swap is a disk area the OS can use to store pages that do not fit in RAM, and a system can run with virtual memory and no swap at all.
Do Python threads run in parallel?
In standard CPython only one thread runs Python bytecode at a time because of the GIL, so threads help with I/O-bound work but not CPU-bound work. Use multiprocessing for CPU work; Python 3.13 added an optional free-threaded build without the GIL, officially supported since 3.14 but not the default.
What is the difference between a mutex and a binary semaphore?
A mutex has an owner, and only that thread should unlock it. A binary semaphore has no owner, so one thread can signal another by releasing it.
Which OS book should I read for interviews?
OSTEP (Operating Systems: Three Easy Pieces) is free online and covers processes, scheduling, virtual memory and concurrency at exactly the right depth.

Go deeper

ShareXLinkedInWhatsApp