目錄表
Thread
0x00 Outline
- Thread 簡介
- Thread vs Process
- Thread 種類
- Multi-threading Model
- Thread Pools
0x01 Thread 簡介
又稱 Lightweight Process,是作業系統能夠進行運算排程的最小單位,它被包含在 process 之中,是 process 中的實際運作單位
- Thread 是作業系統分配 CPU 時間的對象
- Process 是作業系統分配資源的對象
Thread 中包含:
- Thread ID
- Thread State
- Program counter
- Register Set
- Stack
同個 Process 中的 Threads 彼此共享:
- code section
- data section
- operating system resource
(Code section + Data section = memory space, Address space, Heap memory)
Multi-thread 的好處:
- Responsiveness: 允許程式中的某部份被中斷或是執行得非常久時,該程式仍然可以繼續執行,一個 Process 內只要還有一個 thread 在 run,Process 就還可繼續執行
- Resource sharing: Threads 共用所屬 Process 的記憶體和資源
- Economy: Thread 的建立與 context switch 成本都低於 Process
- Utilization of multiprocessor architecture: multi-thread program 可以更能發揮 multiprocessor 效能
0x02 Thread vs Process
一個 Process 中可能包含多條 threads
thread 的 creation, scheduling, context switching 等成本都較 process 低
Process 內的 threads 共享 memory space, Address space, Heap memory, system resource 等,但 process 與 process 間互相獨立,不共享這些資訊
Thread 必須提供對 share data 的互斥存取控制,以防止不正常 thread 存取造成的危害
0x03 Thread 種類
User threads
在 user mode 下進行,作業系統不知道有這些 thread 存在,thread 之間的 scheduling, context switching 等也不需要作業系統介入管理
- 優點: 產生、管理 thread 成本較低,context switch 速度較快
- 缺點: 當 user thread 發出 blocking system call,且 kernel 是 single threaded,會導致整個 process 被 block 住
- 常見的 user threads:
- Pthreads (POSIX threads)
- Win32 threads
- Java threads
Kernel threads
在 kernel mode 下進行,作業系統知道有這些 thread 存在,thread 之間的 scheduling, context switching 由作業系統介入管理
- 優點: 所有 threads 之間可以平均使用處理器 (User thread 對系統來說只看得到 process 所以不管 process 有幾條 threads 還是只會以 process 為一單位去分配 CPU)
- 缺點: context switch 時間成本較高
- 常見的 kernel threads:
- Windows XP/2000
- Solaris
- Linux
0x04 Multi-threading Model
Many-to-one Model
多個 user-level threads 對應到一個 kernel thread
- threads 的管理是在 user space 中進行,context switch 成本低,效率佳
- 容易造成 process 被 single thread blocking system call 鎖住
- 同一時間只有一個 thread 在存取 kernel,無法讓多個 thread 在 multiprocessor 上執行,沒有平行化
One-to-one Model
每個 user-level thread 對應一個 kernel thread
- 可在 multiprocessor 系統中讓多個 threads 同時執行,提供比 Many-to-one Model 更多的平行性
- 當一個 thread blocking 時,其他 thread 仍可繼續執行
- 產生一個 user thread 時,需連帶產生一個 kernel thread,會佔用較多資源
- 為了控制系統資源的使用,此模式通常會限制執行緒產生的個數
Many-to-many Model
多個 user-level thread 對應到較少或相同個數的 kernel threads
- 多個 user-level thread 可以在較少或相同個數的 kernel threads 間進行切換
- 可以對每個 process 限制其對應 kernel threads 的數量,也可以對整個作業系統限制 kernel threads 的總量
- 可在 multiprocessor 系統中讓多個 threads 同時執行
0x05 Thread Pools
產生多個 threads 並將這些 threads 放到一個 Pool 中等待工作
需要時可以喚醒一個 thread,這比重新產生一個 thread 快速
Thread Pool 限制了任何時間點上 thread 的個數,不會讓系統資源耗盡
Thread Pool 中 thread 個數可以根據:
- CPU 數量
- 實體記憶體大小
- 預期需求數