Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 核心等待佇列機制詳解:資料結構、API 與實作流程圖解

編輯:Linux 教學

等待佇列是核心同步基礎設施,支援任務在條件滿足前睡眠、條件達標後喚醒。核心兩大資料結構:

資料結構

struct __wait_queue_head {
    spinlock_t lock;              // 保護佇列的自旋鎖
    struct list_head task_list;   // 掛載等待任務的鏈表頭
};

struct __wait_queue {
    unsigned int flags;
    void *private;                // 通常指向 task_struct
    wait_queue_func_t func;       // 喚醒回調 (通常 autoremove_wake_function)
    struct list_head task_list;   // 掛入 wait_queue_head 的節點
};

核心流程

  1. 定義佇列頭:DECLARE_WAIT_QUEUE_HEAD(name) 靜態初始化,或動態 init_waitqueue_head()。
  2. 任務呼叫 wait_event(wq, condition):
     ① 以當前 task_struct 初始化 wait_queue;
     ② 鎖保護下掛入佇列;
     ③ 判斷條件,滿足則移出返回;
     ④ 不滿足 → 排程睡眠;
     ⑤ 被喚醒後重複 ②③,直到條件滿足。
  3. 喚醒端呼叫 wake_up(wq) (喚醒一個) 或 wake_up_all(wq) (喚醒全部),將任務設為可執行並移出佇列。

主要 API 速查

介面功能
wait_event(wq, condition)睡眠等待條件滿足 (不可中斷)
wait_event_timeout(wq, condition, timeout)帶超時機制
wait_event_interruptible(wq, condition)可被訊號中斷,返回 -ERESTARTSYS
wait_event_interruptible_timeout(...)可中斷 + 超時
wake_up(wq)喚醒佇列中一個任務
wake_up_all(wq)喚醒佇列中所有任務

等待佇列廣泛應用於驅動程式、檔案系統、網路協定棧等核心子系統,理解其運作對核心開發與除錯至關重要。

Copyright © Windows教程網 All Rights Reserved