# Process Concept
## Process vs. Program
- Program: binary stored in disk(a passive entity)
- Process: a executing program in memory(an active entity)
-
---
## Process includes
1. Process在memory空間裡面的content(不同區塊)
- Code segment (text section)
- 也就是平常寫的程式碼,先被載入到記憶體裡面等著被CPU fetch
- Data section: Global Variable
- Stack: local variable and function
- Heap: dynamic allocated variables or classes
2. 一些meta data(管理process的資料)
- <span style="color:orange">**program counter, register contents**</span>
- a set of associated resources (e.g. open file handlers)

---
## Threads
- a.k.a <span style="color:orange">lightweight process</span>: a basic unit of CPU utilization (thread是使用CPU的最小單位)
- 同一個parent process的thread,預設會共享一記憶體空間,而這一塊空間在形成的時候就會被分配好
- Thread共用的部分:
code section, data section, OS resources
- Thread獨立的部分:
thread ID, program counter, register set, and stack
---
## Process State
- <span style="color:orange">New</span>: the process is being created
- load into memory, allocate space, initialization, etc
- <span style="color:orange">Ready</span>: wait in queue to be assigned to a processor
- <span style="color:orange">Running</span>: instructions being executed by CPU
- <span style="color:orange">Waiting</span>: the process is waiting for events to occur(e.g. I/O)
- <span style="color:orange">Terminated</span>: the process has finished execution

### Note:
- Only one process is running on any processor at any instant
- But many processes may be ready and waiting
---
## Process Control Block(PCB)
**當process被創建的時候,OS就會去建立一個PCB用來管理process。所謂的「process被放進queue」其實是指<span style="color:orange">「PCB被放入queue裡面」</span>,而不是整個process的記憶體空間被放進去。<span style="color:orange">串接的資料結構為linked list**</span>
PCB主要會含有以下資訊:
- Process state
- Program counter
- CPU registers
其他資訊:
- CPU scheduling information (e.g. priority)
- memory management information (e.g. base/limit register)
* 只有在running state的時候才會把這兩個值從 memory load 進 CPU 的 register
- I/O status information
- accounting information
這些資訊只有 OS 需要知道,所以會放在 kernel的記憶體空間裡面
---
## Context Switch
CPU一次只能執行一個Process,要<span style="color:orange">切換</span>給另一個Process時(<span style="color:orange">透過**Interrupt**或是**System call**</span>),必須將process state存入PCB,或是載入其他Process的資訊,這個動作稱為「Context Switch」

- 在做context switch的時候,對process來說都是在閒置
### Note
- Context Switch: Kernel saves the state of the old process and loads the saved state for the new process
- Context Switch time is purely <span style="color:orange">overhead</span>
- 無法避免,但需要減少切換的時間
- Switch time depends on
- memory speed
- number of registers (difficult for current computers since current CPU has more registers)
- existence of special instructions
- a single instruction to save/load all registers
- <span style="color:orange">hardware support</span>
- multiple sets of registers,可以一次紀錄多個process state的狀態,快速地在register之間切換,就不需要經過memory access