Threads vs Processes Explained

A Thread: A Single Path of Execution Within a Process

A process (covered earlier in this section) has its own memory space, open files, and other resources. A thread is a single sequential path of execution running within that process - a process can contain just one thread, or many threads all running concurrently, sharing the same process resources.

What Threads Share vs What Stays Private to Each

Process
+--------------------------------------------------+
| Shared: memory space, open files, global data     |
|                                                    |
|  [Thread 1: own stack, own registers]             |
|  [Thread 2: own stack, own registers]             |
|  [Thread 3: own stack, own registers]              |
+--------------------------------------------------+

All threads within one process share that process's memory and open files - but each individual thread keeps its own private stack and its own set of CPU register values, since each is independently executing its own sequence of instructions.

Why Threads Are Considered "Lightweight" Compared to Processes

Creating a new process means setting up an entirely new, separate memory space. Creating a new thread within an existing process reuses that process's already-existing memory and resources - meaningfully cheaper to create, and switching between threads of the same process is typically faster than a full process context switch (covered earlier in this section).

Why an Application Would Use Multiple Threads at All

  • Responsiveness - one thread can keep handling user input while another thread does slow background work.
  • Resource sharing - threads within one process can share data directly, in memory, without needing the more complex inter-process communication mechanisms (covered in their own dedicated section).
  • Genuine parallelism - on a multi-core processor, separate threads can run truly simultaneously on different cores, not just take rapid turns.

The Trade-off: Shared Memory Also Means Shared Risk

Because threads share the same memory directly, one thread can accidentally interfere with another thread's data if they aren't carefully coordinated - a genuine risk explored in depth in the race conditions note later in this section.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.