What is the difference between a process and a thread?
Short answer: A process is a running program with its own virtual address space and resources (open files, signal handlers, credentials). A thread is a path of execution inside a process; all threads of a process share its memory and open files, but each has its own stack, registers (including the program counter) and scheduling state. Threads are cheaper to create and switch, but a bug in one thread can corrupt the others.
| Process | Thread | |
|---|---|---|
| Address space | own (isolated) | shared with other threads of the process |
| Open files, signal handlers, cwd | own | shared |
| Stack, registers, PC | own | own |
| Thread-local storage, signal mask | – | own |
| Creation cost | higher (new page tables; copy-on-write helps) | lower |
| Context switch | may need a TLB/ASID change | same address space: cheaper |
| Failure | a crash affects only that process | a crash (e.g. segfault) kills the whole process |
| Communication | IPC (pipes, sockets, shared memory) | shared variables + locks |
In Linux both are "tasks" (struct task_struct). fork() and pthread_create() both call clone(); the flags decide what is shared. pthread_create passes CLONE_VM | CLONE_FILES | CLONE_FS | CLONE_SIGHAND | CLONE_THREAD ..., so the new task shares memory and files. Each thread has its own TID; getpid() returns the thread-group ID, which is the same for all threads.
What two threads of the same process share (a common multiple-choice question): code, global and static variables, heap, open file descriptors, and the current directory. They do not share their call stacks or register state (and each has its own small kernel bookkeeping such as thread_info).
When to choose which
- Threads: work that shares a lot of data and needs low-latency communication (a UI thread plus worker threads, parallel computation).
- Processes: isolation and robustness (a crash in one service does not take down the others), privilege separation (a small privileged process plus an unprivileged worker), running different programs.