What is the difference between a process and a thread in Linux?
Processes: isolated and independent
A process is a running instance of a program. It has its own virtual address space, file descriptors, and security attributes. The kernel schedules processes independently, and they communicate through inter-process communication (IPC) mechanisms like pipes, sockets, or shared memory.
In Linux, processes are created with fork() (or clone()), which duplicates the parent. Each process has a unique PID. You can see them with ps, top, or htop.
Threads: shared memory, lighter weight
A thread is a separate flow of execution within a process. Threads share the same address space, file descriptors, and signal handlers, but each has its own stack and registers. This makes communication between threads fast (just shared variables) but requires careful synchronization to avoid race conditions.
Linux implements threads as tasks that share resources; from the kernel's perspective, threads are just processes created with clone() and specific flags. Tools like ps -eLf or top -H show individual threads.
- Process: isolated memory, own PID, slower to create
- Thread: shared memory, own TID, faster to create
- Process communication: pipes, sockets, shared memory
- Thread communication: shared variables, mutexes, condition variables
- Context switch between threads is cheaper than between processes
Common mistakes
- Assuming threads are always faster: they help with I/O-bound tasks but can suffer from lock contention and are harder to debug.
- Thinking a process cannot have multiple threads: modern Linux programs often use many threads within one process.
- Believing threads have separate memory: they share the heap and global variables, which can lead to data races if not synchronized.
