作業系統工程-Thread
Table Of Content
rt-thread github links
先放上 struct Thread 在 rtdef 中的定義
thread 大致觀念
process state
狀態 |
描述 |
初始狀態(initial) |
thread 剛被 created (RT_THREAD_CREATE) ,還沒開始執行時,就處於初始狀態;在此狀態 thread 不參與調度。在 RT-Thread 中的宏定義為 RT_THREAD_INIT |
就緒狀態(ready) |
thread 按照優先級排隊,等待被執行;一旦當前 thread 執行完畢(finish running) 讓出處理器, OS 會尋找最高優先級的 ready state 的 thread 執行。在 RT-Thread 中的宏定義為 RT_THREAD_READY |
執行狀態(running) |
thread 當前正在執行。單核系統中,只有 rt_thread_self() 函數返回的 thread 處於運行狀態;多核系統中,可能就不止這一個 thread 處於運行狀態。在 RT-Thread 中的宏定義為 RT_THREAD_RUNNING |
掛起狀態(hanging/waiting) |
因為該 thread 的資源不夠,thread 不可被執行而掛起(等待),或 thread 主動延時一段時間而掛起。在此狀態 thread 不參與調度。在 RT-Thread 中的宏定義為 RT_THREAD_SUSPEND |
關閉狀態(exit/delete/detach) |
當 thread 執行結束時將處於關閉狀態。在此狀態 thread 不參與調度。在 RT-Thread 中的宏定義為 RT_THREAD_CLOSE |
- RT-Thread 提供 OS 使用的 function,使得 process state 在這五個 state 之間切換。
- 狀態的轉換如下圖所示:

- 下方 process 程式碼的介紹就會按照這張圖的順序一一解釋
補充說明 process 的錯誤碼(error return)
- 一個 thread 就是一個執行場景,錯誤碼是與執行環境密切相關的,所以每個線程配備了一個變量用於保存錯誤碼,線程的錯誤碼有以下幾種:
補充說明 process 優先級(priority)
- 表示 thread 能夠進入 runnging 的先後順序。
每個 thread 都具有優先級, thread 越重要,賦予的優先級就應越高, thread 被使用的可能性才越大。
- RT-Thread 最大能夠使用 256 個 thread priority(0~255),數值越小的優先級越高(0 為 highest priority)。
(若整體 resource 較少的 system 可以只使用 8 或 32 priority)
- 若有比當前 thread priority 更高的 thread 在 ready state 時,當前 priority 較小的 thread 將立刻被 swap out,讓 high priority thread 使用 CPU(processor) 執行。
初始化 thread 的函式
In Initial State
1. Create:創一個 new process
- 上方為呼叫 create function 時得放入的參數(指標函數)
2. Initial:初始化 process
- 下方為呼叫 initial function 時得放入的參數(指標函數)
- 下面把傳入的參數放到 thread 的參數裡面
如 entry、stack
From Initial to Ready State
Start Up
和 Waiting State 有關的函式
From Ready to Wating State
1. Suspend
- 使用時機:在準備狀態的 process 因持有的 resources 不足而無法執行,將被放入 waiting queue。
From Running to Wating State
1. Delay
2. Take
From Wating to Ready State
1. Resume
2. Release
-
和 Exit State 有關的函式
From Running to Exit State
1. Exit
From Waiting to Exit State
1. delete
2. detach
set hook