CodePark/ questions / Processes & threads
START PRACTICINGPRACTICE
Backend question · OS, networking & Linux › Processes & threads

What is the difference between a process and a thread?

A process is a running program with its own resources. A thread is one line of execution inside a process. A process can have many threads.

Each process has:

  • its own virtual address space (the memory the process sees as its own)
  • its own file descriptor table (the list of files and sockets it has open)
  • its own credentials (the user and group it runs as)
  • at least one thread

The kernel isolates processes from each other. One process cannot read another's memory. The only exception is when they set up sharing on purpose, for example with shared memory or pipes.

Threads of the same process share the address space, the heap, global variables and open file descriptors. Each thread has its own stack, its own registers and its own program counter (the address of the next instruction to run). On Linux, the kernel schedules both as tasks. A thread is just a task created with clone() flags that tell it to share the parent's memory.

Pros of threads:

  • They are cheaper to create.
  • Switching between them is cheaper.
  • They can share data directly.

Cons of threads: shared data needs synchronization (locks and similar tools). Also, a crash or a wrong memory write in one thread can bring down the whole process.

Processes give you isolation. The cost is that communication between them is more expensive.

  • A process has its own virtual address space and resources, and the kernel isolates it from other processes.
  • Threads in one process share memory, the heap and file descriptors, but each thread has its own stack and registers.
  • Threads are cheaper to create and switch between, while processes are isolated from each other.
  • Memory shared between threads needs synchronization.