Processes & Threads
Understanding programs in execution, logical control flows, and CPU context switching.
Process & Thread
Process
Program under execution, which has been loaded into RAM from disk and given resources by the OS.
=> Compiled Code. Ready to execute=> Stored in Disk
Thread
A light-weight process. Thread is used to achieve parallelism by dividing a process's tasks which are independent paths of execution.
=> Multiple threads perform these tasks simultaneously.
Visualizing Threads in an Application
The "Save to cloud" thread can do this work as it is a totally independent task and can be executed independently without any interruption (asynchronous work).
├── Main Thread
└── Sub-task Thread (Independent process, e.g., save to cloud)
Why Threads? (Image Conversion Analogy)
Scenario: Convert 200x100 JPG image to 100x100 PNGs
Platform converts 100x100 JPG image to 100x100 PNG. We have a 200x100 image, so we split it into two 100x100 images (A and B).
Total Time: 10 + 10 = 20 seconds
Total Time: 10 seconds (Running concurrently)
In a single CPU system we can perform multi-tasking, but the same concept of time quantum sharing works and it will not cause any physical gain in execution speed for CPU-bound tasks.
Multi-Tasking vs Multi-Threading
| Multi-Tasking | Multi-Threading |
|---|---|
| The execution of more than one task simultaneously is called multi-tasking. | A process is divided into several different sub-tasks called as threads, which have their own path of execution. |
| Concept of more than 1 processes being context switched. | Concept of more than 1 thread. Threads are context switched. |
| No. of CPU: 1 | No. of CPU ≥ 1 (better to have more than 1) |
| Isolation & Memory Protection: OS allocates separate memory & resource to each program. | No Isolation & Memory Protection: OS allocates memory to process, multiple threads of that process share the same memory & resources. |
Thread Scheduling & Context Switching
Thread Scheduling: Threads are scheduled for execution based on their priority. Even though threads are executing within the runtime, all threads are assigned processor time slices by the Operating System.
| Thread Context Switching | Process Context Switching |
|---|---|
| OS saves current state of thread & switches to another thread of same process. | OS saves current state of process & switches to another process by restoring its state. |
| Doesn't include switching of memory space. | Includes switching of memory address space. |
| Fast switching | Slow switching |
| CPU cached state is preserved. | CPU's cache state is flushed. |