What is the difference between a process and a thread?
A process is a running program with its own memory. A thread is a unit of work inside a process; threads of the same process share that memory, so they are lighter to create but need care to avoid clashing.
Explain it simply
A process is like a restaurant: its own kitchen, fridge and staff. Two restaurants do not share ingredients. Threads are the cooks inside one restaurant: they share the same kitchen and fridge, so they can work together quickly, but two cooks grabbing the same pan at the same time causes trouble.
Example
When you open a browser, the browser often starts separate processes for different tabs, so one crashing tab does not bring down the others. Inside one tab, several threads can run: one draws the page, another decodes images, another talks to the network. They share the tab's memory, which makes sharing data fast.
A simple way to picture it:
- Process A: memory for code, data and heap; threads T1 and T2 share it, each with its own stack.
- Process B: completely separate memory; it cannot read Process A's variables without inter-process communication.
How it works
- Each process has its own address space, open files and resources. The operating system isolates processes from each other.
- Each thread has its own program counter, registers and stack, but shares the heap, global data and files with other threads in the same process.
- Switching between threads of the same process is cheaper than switching between processes, because the memory map does not change.
- Processes talk through inter-process communication: pipes, sockets, shared memory or message queues.
Real-world use
- Web servers use threads or thread pools to handle many requests at once.
- Chrome uses multiple processes for safety and stability.
- Node.js runs JavaScript on one main thread and uses a thread pool for file and crypto work.
Common mistakes
- Thinking threads are always faster. Too many threads cause context-switching overhead.
- Forgetting synchronisation. Shared data needs locks or atomic operations to avoid race conditions.
- Mixing up concurrency (dealing with many things at once) and parallelism (actually running at the same moment on multiple cores).
What to say in the interview
"A process is an independent program in execution with its own address space and resources. A thread is the smallest unit of execution inside a process. Threads of one process share code, heap and open files but each has its own stack and registers. Threads are cheaper to create and switch, and communicate through shared memory, but that sharing needs synchronisation to avoid race conditions. Processes are isolated, which is safer, and communicate through IPC."
Follow-up questions
- What is a race condition and how do you prevent it?
- What is context switching?
- What are user-level and kernel-level threads?