Note on Concurrency: Processes and Threads

1. Key Concepts

  • Concurrency involves two main components: Processes and Threads.

2. Processes

  • A process is an instance of a running program, i.e., the execution of a program.
    • Example: Different processes can be seen running simultaneously on your computer for the programs you are using.
  • Characteristics:
    • Isolated: Each process has its own private memory space.
    • No data sharing: Processes do not share data with other processes.
    • Resource-heavy: Processes consume more resources, especially if they are “heavyweight.”
    • Managed by CPU/OS: The CPU and operating system can run multiple isolated processes at the same time (also referred to as “programs”).

3. Threads

  • A thread is a part of execution inside a program or a “subprocess.”
    • It executes a specific piece of code.
    • Multiple threads can run concurrently within a single program.
  • Characteristics:
    • Shared resources: Threads share data and memory with other threads within the same process.
    • Lightweight: Threads consume fewer resources compared to processes.
    • Concurrency implementation: Threads enable programmers to implement concurrency in applications.
      • Example: In a product lookup program:
        • One thread fetches data from the database.
        • Another thread handles the user interface.
        • This allows query execution to occur while the application remains responsive to user input.
    • Multithreading: Switching between threads happens very quickly, enabling efficient program execution.

4. Comparison: Processes vs. Threads

AspectProcessThread
DefinitionAn isolated instance of a running program.A part of execution within a program.
MemoryPrivate memory space; no sharing.Shares memory and data with other threads.
Resource UsageHeavyweight; consumes more resources.Lightweight; consumes fewer resources.
ConcurrencyManaged by the OS/CPU.Enables concurrent tasks within a program.
ExampleRunning multiple apps (e.g., browser, editor).Concurrent tasks in one app (e.g., UI rendering, data fetching).

5. Practical Example

  • A program may spawn multiple threads to perform different tasks simultaneously:
    • Thread 1: Renders the User Interface (UI).
    • Thread 2: Fetches data from the database.
    • Thread 3: Handles file uploads.
  • These threads operate within the same process, sharing memory and resources efficiently.

6. Summary

  • Processes are isolated executions of programs, managed by the OS/CPU, and are resource-intensive.
  • Threads are lightweight units of execution within a process, enabling concurrency and efficient resource usage.
  • Multithreading allows fast switching between threads, making program execution more efficient.

Key Takeaway: Processes provide isolation but are resource-heavy, while threads enable efficient concurrency within a process by sharing resources.