1.3Threads versus processes
The idea
A thread is a lightweight stream of execution inside a process. Threads of one process share the address space but have their own stack and registers.
Think of it like this: Several cooks in one kitchen: they share the ingredients and stove (address space), but each has their own recipe card and place in it (stack, program counter).
Why it exists
Creating and switching threads is cheaper than processes, and they can share data without system calls, so servers use them heavily.
How it works
- Shared: code, global data, heap, open files.
- Private: stack, registers, program counter, thread id.
- User-level threads: managed by a library, fast, but a blocking call blocks the whole process and no parallelism.
- Kernel-level threads: scheduled by the OS, can run in parallel and block individually.
Worked example: Two threads each have a local variable and a global variable
The two copies of the local variable live on different stacks and are independent. The global is one shared location, so unsynchronised updates race.
Now play with it
- →Read the table row by row and say "shared" or "private" before looking at the answer.
- →Notice why a thread crash can kill the whole process.
| Resource | Process | Thread (within one process) |
|---|---|---|
| Address space, code, data, heap | own | shared with the other threads |
| Open files, signals | own | shared |
| Stack | own | own, one per thread |
| Registers and program counter | own | own |
| Creation and switch cost | high | low |
| Communication | needs IPC (pipes, messages, shared memory) | just read and write shared variables |
| A crash | kills only that process | can kill the whole process |
User-level threads: fast to switch, but one blocking system call blocks every thread and they cannot use several cores. Kernel threads are scheduled individually.
Check yourself
A user-level thread calls a blocking read(). What happens?
Exam notes (the dense version)
A thread is a unit of CPU execution inside a process. Threads of one process share code, data, heap, open files and the address space; each has its own stack, registers and program counter. Thread creation and switching are cheaper than for processes and sharing needs no IPC, but one thread can corrupt the others. User-level threads are invisible to the kernel (fast, but one blocking call blocks all, no multi-core use); kernel-level threads are scheduled by the kernel.
Previous year questions: Processes, Threads & System Calls (15)
PYQs are grouped by topic, so this is the full set for Processes, Threads & System Calls; try the ones that match this subtopic. Open all 15 on the topic page.