Processes and Threads

Learn what a process is, how threads differ, how the OS switches between them, and the role of system calls and the kernel.

Beginner · about 6 hours · difficulty 2/5

An operating system manages hardware and gives programs a clean, isolated environment. Most interview OS questions start here, so get the vocabulary precise.

Core ideas

  • Kernel vs user mode: user programs cannot touch hardware directly; they ask the kernel via system calls (read, write, fork, exec). Switching into kernel mode has a cost.
  • Process: a running program with its own address space (code, data, heap, stack), open files and a Process Control Block (PCB) holding its state, registers and scheduling info.
  • Process states: new, ready, running, waiting (blocked), terminated. Be able to draw the transitions.
  • Thread: a unit of execution inside a process. Threads share code, heap and open files but each has its own stack and registers. Creating and switching threads is cheaper than processes.
  • Context switch: saving one task's registers and loading another's. It is pure overhead, which is why too many threads can slow a system down.
  • fork() creates a child process that is a copy of the parent (with copy-on-write pages); exec() replaces the program. A classic question: how many times does "hello" print after three fork() calls? (8.)

Also know

  • Zombie process (finished, parent has not called wait) vs orphan process (parent died first).
  • User-level vs kernel-level threads, and multithreading models.
  • Inter-process communication: pipes, shared memory, message queues, sockets, signals.

Good enough to move on: you can explain process vs thread with what each shares, draw the state diagram, and describe what happens during a context switch.

Key concepts

  • Kernel, user mode and system calls
  • Process, PCB and address space
  • Process states and transitions
  • Threads vs processes
  • Context switching
  • fork, exec and wait
  • Zombie and orphan processes
  • Inter-process communication

Mini project

On Linux or WSL, write a C program that forks children, has each run a different command via exec, and waits for them; then write a two-thread program with pthreads or std::thread and print which values are shared and which are per-thread.

Check yourself

What exactly do two threads of the same process share, what do they not share, and why is a thread switch cheaper than a process switch?

Free resources