How a process differs from a thread

· 3 min read

#how-it-works#os

A process is a running program together with the resources it needs. A thread is one line of execution inside it. The idea to keep: a process owns its memory, and the threads inside it share that memory.

The short version

The operating system creates a process when a program starts. The process gets its own virtual address space, its code, open handles, a security context and a process ID, and it begins with one thread. That thread is what the system schedules to run. A program can start more threads. They share the process's address space and system resources, and each one has its own stack and registers.

Threads share memory inside a process Process A contains one shared box for the heap and open files and two thread boxes, each with its own stack, and both threads point to the shared box. Process B is a separate box with its own memory space. A dashed line between the two processes is labelled separate memory. Process A Shared heap and files Thread 1 own stack Thread 2 own stack Process B Own memory space separate memory
Simplified: the threads of Process A share one heap and its open files, while Process B has a memory space of its own.

Step by step

  1. The system creates a process with its own address space and one primary thread.
  2. The program starts more threads when it wants work to run side by side.
  3. All threads in the process see the same heap and the same open files.
  4. Each thread has its own stack and registers, so each one tracks its own place in the code.
  5. A second process gets a separate memory space: after a fork, a write in one does not appear in the other.
Process Thread
Memory Its own address space Shares the address space of its process
Stack and registers One set per thread Its own
Open files Belong to the process Shared by all threads of that process
Scheduled by the system Through its threads Yes, the unit that gets scheduled

Why it matters

My reading: shared memory makes handing data between threads easy, and it also means one thread's write is visible to all the others. Separate processes cannot overwrite each other's memory.

Sources