Understanding Processes and Threads

A comprehensive guide to processes, threads, and their differences

Featured image



🎯 Overview

Understanding the differences between processes and threads is crucial for software development. Let’s explore these concepts in detail.

💡 Program vs Process

A program is a set of instructions stored on disk, while a process is a running instance of a program. Key differences:



🔄 Process vs Thread

HTTPS

Process

Thread



📊 Comparison Table

🔑 Aspect 🖥️ Process 🧵 Thread
Definition Program instance in execution Smallest unit of programmed instructions
Memory Separate memory space Shared memory within process
Creation Resource-intensive Lightweight
Communication Complex (IPC) Simple (shared memory)
Control Controlled by Operating System Controlled by Process
Overhead High Low
Use Case When isolation is needed For concurrent tasks
Failure Impact Failure is isolated Failure affects other threads



📈 Process States

1. NEW
   - Process being created

2. READY
   - Waiting for processor

3. RUNNING
   - Currently executing

4. WAITING
   - Waiting for event

5. TERMINATED
   - Execution completed



🔄 Multi-Threading vs Multi-Processing

Multi-Threading

Multi-Processing



🔄 Context Switching

Context Switching is the process where the CPU switches from one process or thread to another. It involves storing the state of the current process and loading the state of the next process.

sequenceDiagram participant P1 as Process P1 participant S as Scheduler participant P2 as Process P2 P1->>S: ⏳ Time Out Note right of S: 🔄 Context Switching P1 to P2 S->>P2: 🚀 Dispatch P2->>S: ⏳ Time Out Note right of S: 🔄 Context Switching P2 to P1 S->>P1: 🚀 Dispatch

🔄 Steps in Context Switching:

  1. Time Out (Preemption):
    • The running process (e.g., P1) reaches its time slice limit.
    • The Scheduler is notified to switch the running process.
  2. Saving State:
    • The state of P1 (CPU registers, program counter, etc.) is saved to memory.
    • This ensures that P1 can resume from where it stopped.
  3. Loading Next Process State:
    • The state of P2 is loaded from memory.
    • P2 is now ready to run.
  4. Dispatching:
    • The CPU starts executing P2.
    • This cycle repeats for process scheduling.

⚠️ Impact of Context Switching:

🔍 Example Use Cases:



⚡ Hyper-Threading

Intel’s implementation of SMT (Simultaneous Multi-Threading):

1. Physical Core Duplication
   - Duplicate register sets
   - Manages multiple thread states

2. Shared Resources
   - Shared execution engine
   - Shared cache

3. Benefits
   - Improved efficiency
   - Enhanced parallelism
   - Better multitasking



📚 Reference