摘自 《在 linux 驅動程式中,可以使用等待佇列(wait queue) 來實現阻塞程序的喚醒.等待佇列很早就作為乙個基本的功能單位出現在 linux 核心裡了,它以隊列為基礎資料結構,與程序除錯機制緊密結合,可以用來同步對系統資源的訪問.
linux 核心提供了如下關於等待佇列的操作.
wait_queue_head_t my_queue;
wait_queue_head_t 是 __wait_queue_head 結構體的乙個 typedef
ps:include/linux/wait.h :
typedef struct __wait_queue_head wait_queue_head_t;
init_waitqueue_head(&my_queue);
使用巨集定義並初始化等待佇列頭部:
declare_wait_queue_head(name)
declare_waitqueue(name, tsk)
定義並初始化乙個名為 name 的等待佇列元素
void add_wait_queue(wait_queue_head_t *q, wait_queue_t *wait);
void remove_wait_queue(wait_queue_head_t *q, wait_queue_t *wait);
add_wait_queue() 用於將等待佇列元素 wait 新增到等待佇列頭部 q 指向的雙向鍊錶中,而 remove_wait_queue() 用於將等待佇列元素 wait 從由 q 頭部指向的鍊錶中移除.
wait_event(queue, condition)
wait_event_interruptible(queue, condition)
wait_event_timeout(queue, condition, timeout)
wait_event_interruptible_timeout(queue, condition, timeout)
第 1 個引數 queue 作為等待佇列頭部的佇列被喚醒,而且第 2 個引數 condition 必須滿足,否則繼續阻塞. wait_event() 和 wait_event_interruptible() 的區別在於後者可以被訊號打斷,而前者不能.加上 _timeout 字尾意味著阻塞等待的超時時間, 以 jiffy 為單位, 在弟 3 個引數的 timeout 到達時, 不論 condition 是否滿足, 均返回.
void wake_up(wait_queue_head_t *queue);
void wake_up_interruptible(wait_queue_head_t *queue);
上述操作會喚醒以 queue 作為等待佇列頭部的佇列中所有的程序
wake_up() 應該與 wait_event() 或 wait_event_timeout() 成對使用, 而 wake_up_interruptible() 應該與 wait_event_interruptible() 或 wait_event_interruptible_timeout() 成對使用. wake_up() 可喚醒處於 task_interruptible 和 task_uninterruptible 的程序, 而 wake_up_interruptible() 只能喚醒處於 task_interruptible 的程序.
sleep_on(wait_queue_head_t *q);
interruptible_sleep_on(wait_queue_head_t *q);
sleep_on() 函式的作用就是將目前程序的狀態置成 task_uninterruptible, 並定義乙個等待佇列元素, 之後把它掛到等待佇列頭部 q 指向的雙向鍊錶, 直到資源可獲得, q 佇列指向鏈結的程序被喚醒.
interruptible_sleep_on() 與 sleep_on() 函式類似, 其作用是將目前程序的狀態置成 task_interruptible, 並定義乙個等待佇列元素, 之後把它附屬到 q 指向的佇列, 直到資源可獲得 (q 指引的等待佇列被喚醒) 或者程序收到訊號.
sleep_on() 函式應該與 wake_up() 成對使用, interruptible_sleep_on() 應該與 wake_up_interruptible() 成對使用.
linux 等待佇列
linux 核心的等待佇列是以雙迴圈鍊錶為基礎資料結構,與程序排程機制緊密結合,能夠用於實現核心的非同步事件通知機制。在這個鍊錶中,有兩種資料結構 等待佇列頭 wait queue head t 和等待佇列項 wait queue t 等待佇列頭和等待佇列項中都包含乙個 list head 型別的域...
linux 等待佇列
linux 核心的等待佇列是以雙迴圈鍊錶為基礎資料結構,與程序排程機制緊密結合,能夠用於實現核心的非同步事件通知機制。在這個鍊錶中,有兩種資料結構 等待佇列頭 wait queue head t 和等待佇列項 wait queue t 等待佇列頭和等待佇列項中都包含乙個 list head 型別的域...
Linux 等待佇列
在閱讀tun驅動時看到,有一些類似 add wait queue 的函式,這些函式正是執行等待佇列的相關操作,要說等待佇列還得從核心程序排程說起,核心排程系統內程序,分配時間片,但是有些程序如從網絡卡中讀資料,在 網絡卡有資料到達之前程序處於阻塞狀態,如果此時給相應程序分配時間片做排程,無疑是浪費系...