目錄表

Thread

0x00 Outline


0x01 Thread 簡介

又稱 Lightweight Process,是作業系統能夠進行運算排程的最小單位,它被包含在 process 之中,是 process 中的實際運作單位

Thread 中包含:

同個 Process 中的 Threads 彼此共享:

(Code section + Data section = memory space, Address space, Heap memory)

Multi-thread 的好處:


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 等也不需要作業系統介入管理

Kernel threads

在 kernel mode 下進行,作業系統知道有這些 thread 存在,thread 之間的 scheduling, context switching 由作業系統介入管理


0x04 Multi-threading Model

Many-to-one Model

多個 user-level threads 對應到一個 kernel thread

One-to-one Model

每個 user-level thread 對應一個 kernel thread

Many-to-many Model

多個 user-level thread 對應到較少或相同個數的 kernel threads


0x05 Thread Pools

產生多個 threads 並將這些 threads 放到一個 Pool 中等待工作

需要時可以喚醒一個 thread,這比重新產生一個 thread 快速

Thread Pool 限制了任何時間點上 thread 的個數,不會讓系統資源耗盡

Thread Pool 中 thread 個數可以根據: